1、父组件的代码
// parent.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.styl']
})
export class ParentComponent implements OnInit {
public inputData = 'inputTest';
constructor() { }
ngOnInit(): void {
}
}
// parent.component.html
<p>
<app-child [inputData]="inputData"></app-child>
</p>
2、子组件的代码
<1>、第一种接收方式,不便于对数据进行切面拦截,inputData可以作为属性在模板中直接使用。
// child.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.styl']
})
export class ChildComponent implements OnInit {
@Input()
public inputData: string;
constructor() { }
ngOnInit(): void {
}
}
// child.component.html
<p>输入的数据是:{{inputData}}</p>
<2>、第二种接收方式,方便于对数据进行切面拦截,inputData不能作为属性在模板中直接使用。
// child.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.styl']
})
export class ChildComponent implements OnInit {
public _inputData: string;
constructor() { }
ngOnInit(): void {
}
@Input() set inputData(data: string) {
// 对从父组件传入的数据进行拦截处理
const temp = data.toUpperCase();
// _inputData可以作为属性在模板中使用
this._inputData = temp;
}
}
// child.component.html
<p>输入的数据是:{{_inputData}}</p>