2.3: Components
Angular has component-based architecture, so our goal is to to have every piece of an application seperated into components. Think about a web application's opening page. How many components could we make out of it? We could have the header, the footer, the content, sidebars...you get the picture.
This is the core idea of Angular, making a complex site broken down into resuable parts. You're not making one single HTML page or one single JavaScript file. Having the application broken down this way makes it very easy to manage and update through the life of the program.
Computer science key term...the above-mentioned approach is an example of separation of concerns. This is a design paradigm for separating a program into different sections, with each of those sections addressing a specific concern. So, a header component is separate from all the other components and its focus is on all aspects of the header. Make sense?
Let's create our first component. Type in the command line ng g component testcomponent/testComponent
. This creates the folder testcomponent and the four main component files. Get into the habit of having your component's name based on its purpose.
In the testcomponent folder, you should see four files:
test-component.component.css - This where you place your styling
test-component.component.html - This is the view that renders to the page
test-component.component.spec.ts - This is the file for creating unit tests
test-component.component.ts - This is the controller, where all of your application's logic is housed
Take a peak at the app.module.ts file:
Notice that TestComponentComponent has been automatically imported in and added to the declarations. This is nice thing about Angular CLI, it does all of the scaffold work for us.
To see the view, enter the following in the app.component.html: <app-test-component></app-test-component>
COMPONENT METADATA
Here's the metadata of the newly created component:
The @Component decorator indicates the class as a component class and specifies its metadata. We have:
selector - This is a CSS selector that tells Angular to create and place an instance of this component wherever the matching tag in the template HTML. In our example,
app.module.html
is where the tag has been placed.templateURL - This points to the location of the component's HTML template. You can also create the HTML inline by placing HTML code within ``. Bear in mind, you would have to change the keyname to template instead of templateURL.
styleURLs - Similiar to the templateURL, this points to the CSS file of the component. Also, you can create inline styles using `` and writing CSS code right there.
Go ahead and play around in the both the test-component HTML and CSS files. Add additional text and styles and see how it renders to the screen.
NEXT SECTION
Last updated