Prerequisite: Prepare an empty Angular project (ng new Angular-course)

First meeting with an Angular component

  1. ** By creating the component command: ****ng g c components/HelloWorld**To generate our first component
  2. Watch for directory changes and generate our component-related files under SRC /app/ Components

  1. hello-world.component.htmlThe content to be displayed by the component
  2. hello-world.component.scssComponent style definition, CSS precompiler can be pre-selected when creating a project
  3. hello-world.component.tsComponent core class
  4. hello-world.component.spec.tsGroup unit test use
  5. Let’s open it up**hello-world.component.ts**The ** component core class takes a look at the content, in addition to the regular import module and creating a ****HelloWorldComponent**Class, is also used**@Component**A decorator.

  1. selector: Annotates the name of the component, which is used when the component is used
  2. templateUrl: Path to annotate the HTML template
  3. styleUrls: The path to the style used by the HTML template. We see that the array format is used, indicating that passing multiple style files should not be a problem
  4. Component files are for now. Components created during Vue development always need to be mounted. Does Angular need to mount them? How do you do that?
    1. Because git repositories are initialized by default when angular projects are created, we can now see another file that has changedapp.module.tsWhen I opened the file, I saw that the newly created component had been automatically mounted globallyappOn.
  5. Now let’s go through the modification**app.component.html**Content to show our own component
    1. emptyapp.component.htmlThe content of the
    2. Remember the name of the component we created? We want to display the component toappInside:<app-hello-world></app-hello-world>
  6. Start the project**ng serve --open**You can see that the page is displaying**hello-world works! 六四运动This is what is automatically generated when our component is created.

Enrich our components

Binding properties

  1. Syntax example: <img [attribute] =”variable“/ >
  2. Add the imgUrl property to the component’s ts file: public imgUrl: string = 'assets/logo.png';
  3. Use this in a component’s HTML template:<img [src]="imgUrl" alt="">
  4. Take a look at our page

The binding event

  1. Syntax example: <button (event)=”fun($event)”
  2. Add it to the component’s TS fileprintfunction
print(event: Event) {
  console.log('[ print ] >>'.'hello world'.'Event type:' + event.type);
}
Copy the code
  1. Trigger by adding a button to the component’s HTML templateprintfunction
<button (click)="print($event)"</button>Copy the code

Two-way binding

  1. Bidirectional binding: attribute binding + event binding, so bidirectional binding syntax is [(attribute)] =”variable
  2. We prepare a component that demonstrates bidirectional binding:ng g c components/sizer
    1. Component that we need to pass through@Inout()Decorator to receive data through@OutputDecorator to distribute data to achieve two-way data flow
    2. Component TS code (from Angular Chinese):
export class SizerComponent { @Input() size! : number | string; @Output() sizeChange =new EventEmitter<number>();

  dec() { this.resize(-1); }
  inc() { this.resize(+1); }

  resize(delta: number) {
    this.size = Math.min(40.Math.max(8, +this.size + delta));
    this.sizeChange.emit(this.size); }}Copy the code
  1. Component HTML template code (from Angular Chinese):
<div>
  <button (click) ="dec()" title="smaller">-</button>
  <button (click) ="inc()" title="bigger">+</button>
  <label [style.font-size.px] ="size">FontSize: {{size}}px</label>
</div>
Copy the code
  1. We will demonstrate bidirectional binding by mounting components toappAnd, inappDeclare the fontSizePx variable in the component
<app-sizer [(size)] ="fontSizePx"></app-sizer>
<div [style.font-size.px] ="fontSizePx">Resizable Text</div>
Copy the code
  1. You can see that in the demo
    1. appIn thefontSizePxProperty is passed tosizerIn the component
    2. In the operatingsizerComponent after will againsizeUpdate to theappIn thefontSizePxProperty, and the page updates accordingly

Structural instruction

  1. NgIf(built-in) :
    1. Add attributes to component TS:public isShow: boolean = true;
    2. Add demo code to the component HTML template:
<button (click) ="isShow = ! isShow">{{ isShow ? "Do not display" : "display"}}</button>
<p *ngIf="isShow">Hello World</p>
Copy the code
  1. NgFor(built-in) :
    1. Add attributes to component TS:Public list: Array<String> = [' myarray ', 'Huawei ',' Apple '];
    2. Add demo code to the component HTML template:
<div *ngFor="let item of list; let i = index">
  {{ i }} {{ item }}
</div>
Copy the code
  1. NgSwitch(built-in) :
    1. Add attributes to component TS:public status: number = 1;
    2. Add demo code to the component HTML template:
<div [ngSwitch] ="status">
  <div *ngSwitchCase="0">Waiting for the</div>
  <div *ngSwitchCase="1">Has been completed</div>
  <div *ngSwitchDefault>The unknown</div>
</div>
Copy the code
  1. Features:
    1. One tag and one structural instruction
    2. * mark

Attribute instruction

  1. NgClass
    1. In the component’s style file add:
.class1{
  background-color: chocolate;
}
.class2{
  width: 100px;
  height: 50px;
}
.class3{
  font-size: 20px;
  color: chartreuse;
}
Copy the code
  1. Some styles can be optionally turned on and off by variables when binding in a component’s HTML template
<div [ngClass] ="{ class1: false, class2: true, class3: true }">Try binding a set of classes</div>
Copy the code
  1. NgStyle

Try binding a set of styles to a component HTML template

<div [ngStyle] ="{ 'background-color': 'chocolate', width: '150px' }">Try binding a set of styles</div>
Copy the code
  1. NgModel(for form elements only)
    1. Add attributes to component TS:public value: string = 'hello world';
    2. Add the demo code to the component’s HTML:
<input type="text" [(ngModel)] ="value">
<p>value: {{value}}</p>
Copy the code
  1. Attention needs to be paid tomoduleIn the importFormsModuleOtherwise, the function cannot be implemented
  2. When the page is restored, you can update the content in the input box to update the data bound to the page

The pipe

  1. Pipes in Angular are similar to filters in Vue in that they display data in a specified format and operate with pipe characters
  2. Built-in pipe:
  3. Presentation:
    1. Format the time into a uniform style
<div>DatePipe: {{currentTime | date: "yyyy MM ‐ ‐ dd HH: MM: ss"}}</div>
Copy the code
  1. Convert all strings to lowercase
<div>LowerCasePipe: {{ value | lowercase }}</div>
Copy the code
  1. Uppercase all strings
<div>UpperCasePipe: {{ value | uppercase }}</div>
Copy the code
  1. Convert the object into A JSON string and output it on the page for easy debugging

conclusion

In this chapter we mainly demonstrate the basic use of components, can achieve simple functions, the next chapter we will demonstrate communication between components. How many students still use Angular and would not contact it if it were not for their work? I first learned Angualr in 15 years. There is a point ha, the original is pIA PIA paste code, today the first time to describe more, when the exercise, the expression is not also please correct ha.