组件

angular 最核心的概率是“组件化”,组件通常都是由模版和业务逻辑组成

一、创建组件

1
通过 `ng generate component hello-component` 指令,hello-component为组件名

二、@component 注释

1
2
3
4
5
@Component({
    selector: 'app-hello-component',
    templateUrl: './hello-component.component.html',
    styleUrls: ['./hello-component.component.css']
})

selector: 通过selecter来访问组件 templateUr:组件显示的html styleUrls : 显示时的样式

三、加载组件

在需要显示的,通过上一步定义的selector标签

1
    <app-hello-world></app-hello-world>

四、组件的生命周期

Angular的组件也是有生命周期这个概念。在不同的阶段不同的场景下,可以调用不同的生命周期函数钩子(hook)。

  • constructor:构造器函数,一般用于注入服务
  • ngOnChanges:检测到输入数据变化,首次触发发生在ngOnInit前。注意对象的属性发生变化时监听不到
  • ngOnInit:组件初始化,通常会设置一些初始值
  • ngDoCheck:手动触发更新检查
  • ngAfterContentInit:内容初始化到组件之后
  • ngAfterContentChecked:内容变更检测之后
  • ngAfterViewInit:视图 初始化之后
  • ngAfterViewChecked:视图发生变化检测之后,这个可以用来保证用户视图的及时更新
  • ngOnDestroy:组件注销时的清理工作,通常用于移除事件监听,退订可观察对象等

五、组件通信

1.父组件到子组件:父组件用属性绑定将值传入,子组件通过@Input来接收。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//父组件
import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'app';
}
//子组件
import { Component, OnInit ,Input} from '@angular/core';

@Component({
    selector: 'app-hello-component',
    template: `
        <h1>Title:{{ title }}</h1>`,
    styleUrls: ['./hello-component.component.css']
})
export class HelloComponentComponent implements OnInit {
    @Input() title : string;
    constructor() { }

    ngOnInit() {
    }

}  

2.子组件到父组件:子组件自定义事件用@Output传出,父组件用事件绑定获取。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//子组件
import { Component, OnInit ,Input,Output, EventEmitter} from '@angular/core';

    @Component({
    selector: 'app-hello-component',
    template: `
        <button (click)="outputData()"  >hello-component</button>
        `,
    styleUrls: ['./hello-component.component.css']
    })

    export class HelloComponentComponent implements OnInit {
        @Input() title : string;
        data : string = 'im am hello-component';
        @Output() goOut = new EventEmitter();
        constructor() { }

        ngOnInit() {
        }
        outputData(){
        this.goOut.emit(this.data);
    }
}
//父组件
import { Component } from '@angular/core';
@Component({
    selector: 'app-root',
    template: `
    <app-hello-component
        [title]="title"  
        (goOut)="getgoOut($event)"></app-hello-component>
    `,
    styleUrls: ['./app.component.css']  
    })

    export class AppComponent {
        title = 'app';
        getgoOut(event){
        console.log(event);
    }
}