Angular2.0—父子传参

Angular2.0—父子传参

  1. 首先使用脚手架创建项目

友情链接:Angular2.0 —构建项目的流程以及使用ng-zorro

  1. 创建组件news组件和zizujian组件,以及编写路由

友情链接:Angular2.0—路由跳转

  1. 父传子 —— 自定义属性
// news.html

 //引入子组件,自定义属性

child

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

@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.scss']
})
export class NewsComponent implements OnInit {
  
  title = "我是传给子组件的值";
  constructor() { }

  ngOnInit() {
  }

}
//zizujian.html

zizujian works!

{{title}}

//渲染接收的值 // zizujian.ts import { Component, OnInit,Input } from '@angular/core'; @Component({ selector: 'app-zizujian', templateUrl: './zizujian.component.html', styleUrls: ['./zizujian.component.scss'] }) export class ZizujianComponent implements OnInit { @Input() title:string;//接收传过来的值 constructor() { } ngOnInit() { } }
  1. 子传父——自定义事件
//zizujian.ts
import { Component, OnInit,Input,Output,EventEmitter } from '@angular/core';//引入模块

@Component({
  selector: 'app-zizujian',
  templateUrl: './zizujian.component.html',
  styleUrls: ['./zizujian.component.scss']
})
export class ZizujianComponent implements OnInit {
  @Input() title:string;
  //通过EvenrEmitter自定义sends事件
  @Output() sends = new EventEmitter();
  msg;
  constructor() { }

  ngOnInit() {
    this.msg="我是子组件传给父组件的值"
  }
  send(){
        // 发送事件,和参数
    this.sends.emit(this.msg)
  }
}

news.html

//监听事件sends


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

@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.scss']
})
export class NewsComponent implements OnInit {
  msg;
  constructor() { }

  ngOnInit() {
  }
  fu(e){
    console.log(e);//重新赋值
    this.msg = e;
  }
}

你可能感兴趣的:(Angular2.0—父子传参)