五種方式
1. @input
把父組件中的值傳遞到子組件中祸挪,子組件聲明變量時(shí)畴椰,前面用@input裝飾器。
例子1:
子組件中
import { Component, Input } from '@angular/core';
import { Hero } from './hero';
@Component({
selector: 'hero-child',
template: `
<h3>{{hero.name}} says:</h3>
<p>I, {{hero.name}}, am at your service, {{masterName}}.</p>
`
})
export class HeroChildComponent {
@Input() hero: Hero;
@Input('master') masterName: string;
}
父組件中
import { Component } from '@angular/core';
import { HEROES } from './hero';
@Component({
selector: 'hero-parent',
template: `
<h2>{{master}} controls {{heroes.length}} heroes</h2>
<hero-child *ngFor="let hero of heroes"
[hero]="hero"
[master]="master">
</hero-child> `
})
export class HeroParentComponent {
heroes = HEROES;
master: string = 'Master';
}
2. setter
結(jié)合@input可以實(shí)現(xiàn)對數(shù)據(jù)的get弃榨,set
例子2:
子組件中
import { Component, Input } from '@angular/core';
@Component({
selector: 'name-child',
template: '{{name}}'
})
export class NameChildComponent {
private _name = '';
@Input()
set name(name: string) {
this._name = (name && name.trim()) || '<no name set>';
}
get name(): string { return this._name; }
}
父組件中
import { Component } from '@angular/core';
@Component({
selector: 'name-parent',
template: `
<h2>Master controls {{names.length}} names</h2>
<name-child *ngFor="let name of names" [name]="name"></name-child>
`
})
export class NameParentComponent {
// Displays 'Mr. IQ', '<no name set>', 'Bombasto'
names = ['Mr. IQ', ' ', ' Bombasto '];
}
這個(gè)例子中箍铲,子組件中定義了一個(gè)私有變量_name雇卷,接受父組件的name,且定義了name的get和set方法颠猴。通過set設(shè)置默認(rèn)值关划,通過get返回定義的_name
3.聲明周期鉤子 ngOnChanges
監(jiān)聽屬性的變化
例子3:
import { Component, Input, OnChanges, SimpleChange } from '@angular/core';
@Component({
selector: 'version-child',
template: `
<h3>Version {{major}}.{{minor}}</h3>
<h4>Change log:</h4>
<ul>
<li *ngFor="let change of changeLog">{{change}}</li>
</ul>
`
})
export class VersionChildComponent implements OnChanges {
@Input() major: number;
@Input() minor: number;
changeLog: string[] = [];
ngOnChanges(changes: {[propKey: string]: SimpleChange}) {
let log: string[] = [];
for (let propName in changes) {
let changedProp = changes[propName];
let to = JSON.stringify(changedProp.currentValue);
if (changedProp.isFirstChange()) {
log.push(`Initial value of ${propName} set to ${to}`);
} else {
let from = JSON.stringify(changedProp.previousValue);
log.push(`${propName} changed from ${from} to ${to}`);
}
}
this.changeLog.push(log.join(', '));
}
}
import { Component } from '@angular/core';
@Component({
selector: 'version-parent',
template: `
<h2>Source code version</h2>
<button (click)="newMinor()">New minor version</button>
<button (click)="newMajor()">New major version</button>
<version-child [major]="major" [minor]="minor"></version-child>
`
})
export class VersionParentComponent {
major: number = 1;
minor: number = 23;
newMinor() {
this.minor++;
}
newMajor() {
this.major++;
this.minor = 0;
}
}
在這個(gè)例子中,通過ngOnChanges
監(jiān)測了兩個(gè)數(shù)據(jù)的變化,并在數(shù)據(jù)變化時(shí),將數(shù)據(jù)打印到日志上.
一旦數(shù)據(jù)有變化,那么ngOnChanges
就會(huì)執(zhí)行,且變化的數(shù)據(jù)會(huì)進(jìn)入到changes對象中.
4.EventEmitter
它是一個(gè)輸出屬性,所以通常帶@Output裝飾器
例子4
子組件
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'my-voter',
template: `
<h4>{{name}}</h4>
<button (click)="vote(true)" [disabled]="voted">Agree</button>
<button (click)="vote(false)" [disabled]="voted">Disagree</button>
`
})
export class VoterComponent {
@Input() name: string;
@Output() onVoted = new EventEmitter<boolean>();
voted = false;
vote(agreed: boolean) {
this.onVoted.emit(agreed);
this.voted = true;
}
}
父組件
import { Component } from '@angular/core';
@Component({
selector: 'vote-taker',
template: `
<h2>Should mankind colonize the Universe?</h2>
<h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3>
<my-voter *ngFor="let voter of voters"
[name]="voter"
(onVoted)="onVoted($event)">
</my-voter>
`
})
export class VoteTakerComponent {
agreed = 0;
disagreed = 0;
voters = ['Mr. IQ', 'Ms. Universe', 'Bombasto'];
onVoted(agreed: boolean) {
agreed ? this.agreed++ : this.disagreed++;
}
}
(onvoted)='onvoted($event)'
中的(onvoted)對應(yīng)子組件中的@Output() onVoted = new EventEmitter<boolean>();
通過this.onVoted.emit(agreed);
觸發(fā), onvoted($event)
對應(yīng)父組件的onvoted
方法.$event
為傳遞參數(shù)的一個(gè)媒介
5.本地變量
用該方法可以在父組件中讀取子組件中的屬性以及方法
例子:5
父組件中
...
template:`
<child #ch></child>
<button (click)='ch.test'>test<button>
`
...
子組件中
import { Component } from '@angular/core';
@Component({
selector:'child'
...
})
export class childComponent{
test(){
console.log(' this is a test')
}
}
通過這個(gè)方法,可以在父組件中,讀取子組件內(nèi)的方法
6.@viewchild()
例子6
import { AfterViewInit, ViewChild } from '@angular/core';
import { Component } from '@angular/core';
import { A } from './A';
@Component({
...
})
export class B implements AfterViewInit{
@ViewChild(A)
private aa: A;
start(){
this.aa.start()
}
}
將子組件作為viewchild 注入到父組件中,就可以通過該對象讀取A組件里的方法以及屬性
7.通過服務(wù)
import { Injectable } from '@angular/core';
通過此編寫服務(wù),在兩個(gè)組件內(nèi)都引入,那么就可以同時(shí)使用這個(gè)實(shí)例,個(gè)人理解為一個(gè)倉庫,組件類似使用者,通過構(gòu)造方法注入后,那么就可以使用它