1.什么是@input
@input的作用是定義模塊輸入,是用來讓父級組件向子組件傳遞內容。
2.@input用法
首先在子組件中將需要傳遞給父組件的變量用@input()修飾
需要在子組件ts文件import中還添加Input
實例:
import {Component, Input, OnInit} from '@angular/core';
例如:
子組件的ts:
@Input() person; //@Input 此命令用來修飾person是用來接收父組件傳遞的值
前面曾經講過ngModel 單向傳值,所以我們還需要在父組件中使用ngModel單向傳值,用子組件的person接收父組件傳遞的值。
父組件ts:
AppPerson = {
name: “Henry”,
color: “yellow”
};
父組件html:
<app-exam [person]=”AppPerson”></app-exam>
子組件html:
<p> {{person.name}} </p> <p> {{person.color}} </p>
運行結果:
由此結果可以看出,子組件屬性person已經成功接收到了父組件AppPerson的值。
簡單的Input完成!