angularjs4+(6)父组件传值给子组件

1. 新建父组件father,子组件son

ng g component father
ng g component son

2.父组件father.component.ts里面定义变量msg和方法run:

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

@Component({
  selector: 'app-father',
  templateUrl: './father.component.html',
  styleUrls: ['./father.component.css']
})
export class FatherComponent implements OnInit {

  public msg="test";
  constructor() { }

  ngOnInit() {
  }

  run(){
    this.msg = "this is from father";
  }

}

3. 父组件father.component.html里面引用son,给son传递msg和run

<app-son [msg]="msg" [run]="run"> </app-son>

4. son.component.ts里引入Input用来接收father的变量和方法:

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

@Component({
  selector: 'app-son',
  templateUrl: './son.component.html',
  styleUrls: ['./son.component.css']
})
export class SonComponent implements OnInit {
  @Input() msg:string;
  @Input() run:any;
  constructor() { }

  ngOnInit() {
    this.run();
    console.log(this.msg);
  }

}

子组件就可以像调用自己定义的变量和方法一样调用父组件定义的变量和方法

发表评论?

0 条评论。

发表评论


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>