首页 > 其他 > 详细

angular 的 @Input、@Output 的一个用法

时间:2018-01-22 00:46:29      阅读:324      评论:0      收藏:0      [点我收藏+]

angular 使用 @input、@Output 来进行父子组件之间数据的传递。

 

如下:

父元素:

<child-root parent_value="this is parent value" (child_emit)="test()"></child-root>

 父元素标签中有一个属性是,parent_value,在子元素中可以使用该值:

<p [title]="parent_value" >this paragraph‘s title is from parent‘s(parent-root) attribute parent_value</p>

 在子元素中,我们 p 标签的 title 属性绑定了父元素的 parent_value 属性,这里要注意了,

[title]="parent_value" 的意思并不是指 title 的值就是 "parent_value" 这个字符串,而是父元素中指定的 parent_value 属性的值。

这里,我们需要做的处理是,在子组件中,使用 @Input 去注解 parent_value 属性,指明这是一个来自父组件的元素。

 

在上面的例子中,父元素也定义了一个属性 child_emit,值是 test(),也就是说这是一个函数调用,在父元素组件中有一个 test 函数,可是我们应该怎么调用呢?我们毕竟没有 child_emit 这种事件,这时候我们就可以在子元素中触发父元素的这个 test 方法的调用。

但是首先我们先要在子元素组件中把 child_emit 使用 @Output 进行注解,然后将其值设为 new EventEmitter,当我们在子组件中去调用 child_emit 方法的时候,父元素中 child_emit 的值的方法(test)就会被调用。

 

源码如下:

child.component.ts

import {Component, EventEmitter, Input, Output} from "@angular/core";

@Component({
  selector: ‘child-root‘,
  template: `    
  <p [title]="parent_value" >this paragraph‘s title is from parent‘s(parent-root) attribute parent_value</p>
  <button class="btn-font-family" (click)="trigger()">点击的时候会触发父元素 example-root 的 child_emit 对应的事件</button>
  `
})
export class ChildComponent {

  @Input()
  parent_value;

  @Output()
  child_emit = new EventEmitter();

  trigger() {
    this.child_emit.emit()
  }
}

  

parent.component.ts

import {Component, Output} from "@angular/core";

@Component({
  selector: ‘example-root‘,
  template: `    
    <child-root parent_value="this is parent value" (child_emit)="test()"></child-root>
  `,
})
export class ParentComponent {
  @Output()
  parent_value;

  test ()  {
    console.log(‘call by emit at ‘ + new Date().toLocaleString())
  }
}

  

完整源码:https://github.com/eleven26/angular-example/tree/master/src/input_output_example

 

angular 的 @Input、@Output 的一个用法

原文:https://www.cnblogs.com/eleven24/p/8326112.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!