Angular @Input讲解及用法

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完成!


posted @ 2021-08-31 09:03  Magi黄元  阅读(847)  评论(0编辑  收藏  举报