zoukankan      html  css  js  c++  java
  • angular父子组件相互传值

    // 调用子组件  向子组件传值和方法的方式
    <app-header [title]="title" [run]="run" [parent]="this"></app-header>

    在子组件中,引入Input,通过@input() 方式引入,即可通过this.xxx使用

    import { Component, OnInit, Input } from '@angular/core';

    @Component({
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.less']
    })
    export class HeaderComponent implements OnInit {
    constructor() { }
    @Input() title: any;
    @Input() run: any;
    @Input() parent: any;
    ngOnInit() {
    }
    getPatrent() {
    this.run();
    this.parent.run(); // 可以直接调用父组件的属性和方法
    }
    }

     子组件向父组件间传值

    1、通过ViewChild获取子组件的方法和属性 

    import { Component, OnInit, ViewChild } from '@angular/core';
    
    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.less']
    })
    export class HomeComponent implements OnInit {
      public title: any = '首页';
      @ViewChild('child', {static: false}) child: any;
      constructor() { }
      ngOnInit() {
      }
      run() {
        alert('父组件');
      }
      getChildValue() {
        this.child.childRun(); // 通过这种方式可以获取到子组件的方法和属性值
      }
      childFun(e) {
        console.log(e);
      }
    }

    2、通过事件广播

    子组件中引入Output和EventEmitter,再使用@Output定义,通过emit分发

     父组件中接收(同vue中的emit)

  • 相关阅读:
    android:descendantFocusability用法简析
    离开自己的安乐窝
    Android Material Design 中文版
    android Material
    jquery 效果网址分享
    Android判断TextView是否超出加省略号
    如何摆脱工具类
    android 框架
    gridview 横向滚动 一行显示
    自定义 spinner
  • 原文地址:https://www.cnblogs.com/cazj/p/11959189.html
Copyright © 2011-2022 走看看