五种方式
1. @input
把父组件中的值传递到子组件中,子组件声明变量时,前面用@input装饰器。
例子1:
子组件中
import { Component, Input } from '@angular/core';
import { Hero } from './hero';
@Component({
selector: 'hero-child',
template: `
{{hero.name}} says:
I, {{hero.name}}, am at your service, {{masterName}}.
`
})
export class HeroChildComponent {
@Input() hero: Hero;
@Input('master') masterName: string;
}
父组件中
import { Component } from '@angular/core';
import { HEROES } from './hero';
@Component({
selector: 'hero-parent',
template: `
{{master}} controls {{heroes.length}} heroes
`
})
export class HeroParentComponent {
heroes = HEROES;
master: string = 'Master';
}
2. setter
结合@input可以实现对数据的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()) || '';
}
get name(): string { return this._name; }
}
父组件中
import { Component } from '@angular/core';
@Component({
selector: 'name-parent',
template: `
Master controls {{names.length}} names
`
})
export class NameParentComponent {
// Displays 'Mr. IQ', '', 'Bombasto'
names = ['Mr. IQ', ' ', ' Bombasto '];
}
这个例子中,子组件中定义了一个私有变量_name,接受父组件的name,且定义了name的get和set方法。通过set设置默认值,通过get返回定义的_name
3.声明周期钩子 ngOnChanges
监听属性的变化
例子3:
import { Component, Input, OnChanges, SimpleChange } from '@angular/core';
@Component({
selector: 'version-child',
template: `
Version {{major}}.{{minor}}
Change log:
- {{change}}
`
})
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: `
Source code version
`
})
export class VersionParentComponent {
major: number = 1;
minor: number = 23;
newMinor() {
this.minor++;
}
newMajor() {
this.major++;
this.minor = 0;
}
}
在这个例子中,通过ngOnChanges
监测了两个数据的变化,并在数据变化时,将数据打印到日志上.
一旦数据有变化,那么ngOnChanges
就会执行,且变化的数据会进入到changes对象中.
4.EventEmitter
它是一个输出属性,所以通常带@Output装饰器
例子4
子组件
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'my-voter',
template: `
{{name}}
`
})
export class VoterComponent {
@Input() name: string;
@Output() onVoted = new EventEmitter();
voted = false;
vote(agreed: boolean) {
this.onVoted.emit(agreed);
this.voted = true;
}
}
父组件
import { Component } from '@angular/core';
@Component({
selector: 'vote-taker',
template: `
Should mankind colonize the Universe?
Agree: {{agreed}}, Disagree: {{disagreed}}
`
})
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)对应子组件中的@Output() onVoted = new EventEmitter
通过this.onVoted.emit(agreed);
触发, onvoted($event)
对应父组件的onvoted
方法.$event
为传递参数的一个媒介
5.本地变量
用该方法可以在父组件中读取子组件中的属性以及方法
例子:5
父组件中
...
template:`
子组件中
import { Component } from '@angular/core';
@Component({
selector:'child'
...
})
export class childComponent{
test(){
console.log(' this is a test')
}
}
通过这个方法,可以在父组件中,读取子组件内的方法
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.通过服务
import { Injectable } from '@angular/core';
通过此编写服务,在两个组件内都引入,那么就可以同时使用这个实例,个人理解为一个仓库,组件类似使用者,通过构造方法注入后,那么就可以使用它