zoukankan      html  css  js  c++  java
  • angular 的 @Input、@Output 的一个用法

    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]="parent_value" (child_emit)="test()"></child-root>
      `,
    })
    export class ParentComponent {
      @Output()
      parent_value = 'value from parent';
    
      test ()  {
        console.log('call by emit at ' + new Date().toLocaleString())
      }
    }

      

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

  • 相关阅读:
    015.Delphi插件之QPlugins,FMX插件窗口
    014.Delphi插件之QPlugins,MDI窗口
    013.Delphi插件之QPlugins,模块化代码示例
    012.Delphi插件之QPlugins,多实例内嵌窗口服务
    011.Delphi插件之QPlugins,延时加载服务
    010.Delphi插件之QPlugins,遍历服务接口
    009.Delphi插件之QPlugins,服务的热插拔
    008.Delphi插件之QPlugins,服务的两种调用方法
    007.Delphi插件之QPlugins,插件的卸载和重新加载
    006.Delphi插件之QPlugins,多服务演示
  • 原文地址:https://www.cnblogs.com/eleven24/p/8326112.html
Copyright © 2011-2022 走看看