Templates for Web-Angular

Templates

        In the above discussion about components, we saw that a template is a string that specifies what is displayed in the component's view area. We see that this string is mainly HTML code, but also contains specific Angular syntax. The runtime system converts it into pure HTML code and inserts it into the DOM. Angular syntax is divided into several different parts, which we will cover one by one.

        The first set are expressions that generate strings to be inserted into HTML code. These include the '{ {' and '}}' syntax we saw earlier . There are mainly four types:

  1. { {expression}} surrounds any TypeScript-like expression that returns a string to be inserted into HTML code. Angular calls this interpolation . This expression is restricted to accessing the current Angular context, typically the component it's in. This expression is not fully valid TypeScript.

  2. [target] = "expression" Assigns the value of a TypeScript-like expression to the target property.

  3. (event) = "statement" specifies that an event handler is assigned to the event. Angular calls this a template statement.

  4. [(target)]= “expression” assigns the value of expression to the target and vice versa. This feature is used when a program can change a value (such as a text field) and the user can change the same value by interacting with the browser. This is called a two-way assignment.

        These three assignment expressions must be used with care. They are dynamic code that updates the Angular object whenever the right side changes. A common mistake is forgetting to use square brackets or brackets. For example, the following two template codes are completely different.

<img src="imageurl"/>
<img [src]="imageurl"/>

        The first code defines a tag with an HTML attribute that is initialized to the given string. In the second code, the target is an Angular object property, which is assigned the string value. In the second example, if the Angular properties change, the displayed image changes as well. This is different from the first example, where the property is only used to initialize the DOM.

        This last point is an important distinction: Angular statements read and update properties of DOM objects. HTML attributes are only used to initialize the DOM when the page loads. These attributes and properties may have the same name, but they only have the same value when initialized until the property is changed by JavaScript or Angular.

        Also note that the objects referenced in these statements must be local to the component. You cannot access global variables. For example, you cannot use console.log() in these statements because console is a global variable. However, you can access some global objects (such as console.log()) by placing the access in the component's member function. For example, you can write a click event for an HTML element in a template:

(click)="doClick()"

        Then in the component class definition we can define the event handler:

doClick(): void {
  ... // 代码执行的内容
  console.log("clicked");
}

        We will demonstrate the four expressions above using a simple example. The goal is to produce the following application display (before and after interaction).

        In this application, text fields allow input and what is entered will be displayed in the text above the text field. When a user clicks on the "Click me!" paragraph on the page, its color will change. The image on the left is the initial view when loading, and the image on the right is the view of the application after typing "hello" in the text field and clicking the "Click me!" paragraph once.

        The code for the component looks like this:

@Component({
  selector: 'app-root',
  template: `<h1>Hello World</h1>
             <p>Welcome to Angular</p>
             <p>Name: {
   
   {name}}</p>
             <input [(ngModel)]="name" placeholder="type here"/>
             <p (click)="doClick()" [class.selected]="clicked">Click me! </p>`,
  styles: [`.selected { color: red; }`]
})
export class AppComponent {
  name: string;
  clicked = false;

  doClick(): void {
    this.clicked = !this.clicked;
  }
}

        There are a few things to note about this code:

  1. The above code cannot run without importing Angular's Forms module. In the next section we will see how to import this module to support tags.
  2. We introduced styles to components. These style definitions will be applied to the view area. In this case, we introduced a style called selected to handle clickable paragraphs.
  3. The label defines the text input area. Angular's two-way binding links a text input field with a field named name in the component class. This ensures that whenever the user changes the text input field (character by character), the component field gets updated and vice versa. The ngModel identifier is an Angular reference to the input field's text value.
  4. Clickable paragraphs have a definition in

    Event handler in tag content. This defines a function as an event handler, which you will see defined in the AppComponent class. We can also define styles as separate source files and use the stylesUrl attribute instead of inline style definitions.

  5. same

    The label has a one-way binding that toggles the selected style based on a boolean property called clicked in the component (defined in the style property above). As you read further, you'll see that this property is toggled by an event handler. This is achieved by using the special word "class" to access the style class associated with the HTML element. You can also use the special word "style" to access individual styles instead of style classes.

        Here's what's in the code block:

<div *ngIf="specialColour=='red'" style="color:red"> Danger!</div>

<span [ngSwitch]="specialColour">
  <span *ngSwitchCase="'red'">Danger</span>
  <span *ngSwitchCase="'green'">Nice</span>
  <span *ngSwitchCase="'blue'">Sky</span>
  <span *ngSwitchDefault>no opinion</span>
</span>

<ul>
  <li *ngFor="let col of colourList">{
   
   {col}}</li>
</ul>

        Additionally, there is a type of Angular expression that can be placed in Angular templates. They are called template statements and are equivalent to control statements in regular programming languages, but these statements apply to views rather than code. There are equivalent statements to the if, for, and switch statements in traditional languages.

        The first statement is an *ngIf statement that includes the element if the associated expression is true. For example, consider the following statement.

<div *ngIf="specialColour=='red'" style="color:red"> Danger!</div>

        You can see that here, *ngIf is used as

        The properties of the label. It takes a TypeScript expression as its value. It works by including the tag's contents in the DOM when the expression is true, but not when the expression is false. Note that this is different from using style changes to hide displayed text (for example, a hidden style class). *ngIf actually removes data from the DOM when the expression is false, which has important performance benefits for complex data.

        The next Angular template statement is the ngSwitch statement. It allows us to specify alternative values ​​to be displayed based on the value of the switch statement. It is a more flexible version of *ngIf, testing values ​​other than just true and false.

        See the example below.

<span [ngSwitch]="specialColour">
  <span *ngSwitchCase="'red'">Danger</span>
  <span *ngSwitchCase="'green'">Nice</span>
  <span *ngSwitchCase="'blue'">Sky</span>
  <span *ngSwitchDefault>no opinion</span>
</span>

        Note that there are three keywords (ngSwitch, *ngSwitchCase, and *ngSwitchDefault). An unusual keyword is ngSwitch, which appears in parentheses as an Angular assignment statement. From your previous programming experience, it should be easy to understand how the switch portion of this code works. Also note that double quotes are required, e.g. "'red'". This is because the property is defined in HTML, and the Angular compiler scans the property's contents as a TypeScript string. Because it's a TypeScript string, it also needs a second set of quotes.

        Finally, the most complex Angular statement is *ngFor. It defines a loop that processes a collection of objects, such as an array. We will demonstrate this statement with an example. Suppose we have the following component definition.

export class AppComponent {
  colourList = ["red", "white", "blue", "black", "green"];
  specialColour = 'green';
}

        This introduces an array of strings that we can manipulate using *ngFor statements. The following component description displays the data in list form. It also demonstrates the *ngIf statement we used above.

@Component({
  selector: 'app-root',
  template: `<h1>List of colours</h1>
             <div *ngIf="specialColour=='red'" style="color:red"> Danger!</div>
             <ul>
             <li *ngFor="let col of colourList">{
   
   {col}}</li>
             </ul>
            `,
})

        This will be displayed in the browser as shown below.

        We can also use some additional syntax to access the index number of the array. For example, if we wanted to print the index number before the array value in the above example, then we could write:

<ul>
  <li *ngFor="let col of colourList; let i=index" style="list-style-type:none">{
   
   {i}}: {
   
   {colourList[i]}}</li>
</ul>

        This will appear as follows:

        Unfortunately we can't just use the index syntax, you have to add "let-of" to the loop string to recognize the assignment of the index.

Guess you like

Origin blog.csdn.net/qq_54813250/article/details/133790944