In this chapter, we will learn how to use Angular2 to show data, and how to use its built-in instructions NgFor and NgIf
First, make sure you have an Angular2 sample program that can be run. It is best to be the QuickStart small project we completed in the previous chapter or the QuickStart small project you completed according to the steps above the official website, because our explanations are based on that basis; then let's start the following happy journey.
Because our series of articles use TypeScript , before reading the following content, you might as well look at the types of TypeScript or ES6. Their URLs are TypeScript and ES6. If you have learned similar object-oriented languages such as Java or C++ before, it will be easy to learn the classes here; the classes here are basically similar to those in those languages.
In the previous section, we exported an empty class in app.component.ts , so we need to start filling it to make it full. First, we add three attributes to the AppComponent class (component), name, age, fruit; just like the following:
export class AppComponent { username = 'dreamapple'; age = 22; fruit = 'apple'}The above writing method is actually just a form of abbreviation, but the complete writing method should be as follows:
export class AppComponent { //username = 'dreamapple'; //age = 22; //fruit = 'apple' username: string; age: number; fruit: string; constructor() { this.username = 'dreamapple'; this.age = 22; this.fruit = 'apple'; }}Then we have to modify our template, because we have to use more HTML in the template, so we have to use backticks to wrap our HTML fragments; our decorator function is as follows:
@Component({ selector: 'my-app', template:` <p>My name is: {{username}}</p> <p>My age is: {{age}}</p> <p>My favorite fruit is: {{fruit}}</p> `})Of course, we can also use the templateUrl configuration options of the metadata object in the decorator function, as shown below:
@Component({ selector: 'my-app', //template:` // <p>My name is: {{username}}</p> // <p>My age is: {{age}}</p> // <p>My favorite fruit is: {{fruit}}</p> //`, templateUrl: 'app/templates/app-template.html'})Among them, app/templates/app-template.html represents the app-template.html file in the templates folder under the root directory of the program (rather than angular2-travel), and then copy the HTML fragment we wrote before.
From the above process, we can see that Angular2 still uses the double braces used by Angular1; it is used as an interpolation symbol, where the interpolation symbol appears is the data we want to display. Next, we need to learn to use the built-in instruction NgFor. Students who are familiar with Angular1 should easily get started with this instruction, because NgFor and ng-repeat are basically the same; it is used to loop an iterable object, which is generally an array.
Next, we add another attribute fruitsList to AppComponent, as shown below:
export class AppComponent { username = 'dreamapple'; age = 22; fruitsList = ['apple', 'orange', 'pear', 'banana']; fruit = this.fruitsList[0]; // Use this.fruitsList[0]}The thing we need to pay attention to is the commented place. We must use this.fruitsList to refer to the attributes we have defined above. If fruitsList is used, Angular will not know what it represents.
Next we are going to loop through this fruit array and see how to represent it in the template.
@Component({ selector: 'my-app', template:` <p>My name is: {{username}}</p> <p>My age is: {{age}}</p> <ul> <li *ngFor="let fruit of fruitsList">{{fruit}}</li> </ul> <p>My favorite fruit is: {{fruit}}</p> `})There are several things that need to be paid attention to in the above code. First, we used *ngFor instead of ngFor. The * here cannot be removed; if it is removed, then our program will not report an error, but we only loop out the first item of the array. Regarding why you need to add *, you can take a look at the template syntax here in detail; of course, we can write some operations behind the *ngFor expression that can help us show each index, which can be like the following:
<li *ngFor="let fruit of fruitsList; let i = index;">{{i}}-{{fruit}}</li>
There are some things to note in the above template code. First of all, you need to know that *ngFor is followed by expressions, so we can write some simple expressions to help us loop better; we also use let keywords, add block-level scope, and limit these variables to the *ngFor loop block. OK, if you want to know more about *ngFor, you can take a look at the official API about NgFor.
The next instruction to be introduced is NgIf. Of course, this instruction is basically similar to Angular1's ng-if instruction. Decide whether to add or remove an element on the DOM based on the value of the following expression.
See how we use this directive in the template:
<p *ngIf="fruitsList.length > 3">fruitsList's length is bigger than 3</p>
<p *ngIf="fruitsList.length <= 3">fruitsList's length is not bigger than 3</p>
First of all, we should point out that, like using *ngFor, we use *ngIf; then we can write an expression after *ngIf, and the expected return result of this expression is a Boolean value; then the *ngIf directive will decide whether to add or remove the element it controls on the DOM based on the value of this expression.
Since we use TypeScript, we can use many new features, such as using classes to build instances; next we will use the Fruit class to build our fruit instance. First, we create a new folder under the app folder, and then we create a Fruit.ts file, where we write the code of the Fruit class:
export class Fruit{ constructor( public name:string, public price: number ){}}Let’s explain the above code. We use the constructor and declare two properties of this object in the constructor; one is name and the other is price. We use the name:string, and price: number parameters in the constructor to create and initialize the properties of this object. Next, we can use this class in our program;
First, introduce this class in app.component.ts:
import {Fruit} from './classes/Fruits';
Then use the Fruit class in AppComponent to initialize our fruit list:
export class AppComponent { username = 'dreamapple'; age = 22; fruitsList = [ new Fruit('apple', 20), new Fruit('orange', 30), new Fruit('pear', 40), new Fruit('banana', 50) ]; //noinspection TypeScriptUnresolvedVariable fruit = this.fruitsList[0].name; // Use this.fruitsList[0]}Then we need to change our template:
The code copy is as follows:
<li *ngFor="let fruit of fruitsList; let i = index;">{{i}}-{{fruit.name}}-{{fruit.price}}</li>
The final result should be the following:
Finally, I have to say that both ES6 and TypeScript make me feel like writing Java; this is also a pro and con. The advantage is that it increases the readability of the code, makes the program easier to maintain, and writes large-scale projects more convenient, making teamwork very convenient. Of course, there are some shortcomings, which mainly increase everyone's learning costs; of course, everything is looking forward.