zoukankan      html  css  js  c++  java
  • angularjs2中的父子组件通信

    父组件模板中引用子组件

     // father  template: ...
    
        <child-item [name] = "fatherItemName" > </child-item>
    
    //...`
    

    其中”fatherItemName” 为父组件中的属性,[name] 为子组件的输入

    在子组件中使用 @Input() name 来接受父组件传递的值

    如果在接收值前需要进行一些处理,可以使用setter 拦截输入属性

    _name: string = '';
    
    @Input()
    
    set nameStr(name: string){
    
    _name = "father name:" + name;
    
    }
    

    这时的 _name 作为临时变量,作为set 和get的中转。其实_name就是我们要组件中要用到的真实属性
    父组件中:
    < child-item [namestr] = “fatherItemName” >
    name -> namestr
    使用getter 输出

    get nameStr(){ return _name; }

    插值时 {{ nameStr }}

    子到父组件之间的数据传递

    1. 事件传值

        // father  template: ...
    
        <child-item (childEvent) = "fatherFunction($event)">  </child-item>
    
        //...
    
          export class FatherComponent{
    
            fatherFunction(){
    
              alert('hello!');
    
          }
    
        }
    

    子组件

        //...
        < p (click) = "clickThis"> click </ p>
        //...
        @Output() childEvent = new EventEmitter<boolean>();
        clickThis(){
        this.childEvent.emit();
        }
    

    2.父组件通过局部变量获取子组件的引用

    <child-item [name] = "fatherItemName" #name > </child-item>
    

    子组件通过#绑定一个name的局部变量来访问子组件的属性

    3.使用@ViewChild 获取子组件的引用

    @ViewChild(ChildComponent)  child: ChildComponent;
    
  • 相关阅读:
    手动添加 memcached.jar包
    easyui返回数据类型
    负载均衡
    nginx负载均衡
    nginx配置文件详解
    Js操作Select大全(取值、设置选中)
    jQuery select的操作代码
    jQuery对Select操作大集合
    PHP+AJAX无刷新返回天气预报
    一个好用的PHP验证码类
  • 原文地址:https://www.cnblogs.com/littlemonk/p/7375486.html
Copyright © 2011-2022 走看看