Angular2.0—父子传参
- 首先使用脚手架创建项目
友情链接:Angular2.0 —构建项目的流程以及使用ng-zorro
- 创建组件news组件和zizujian组件,以及编写路由
友情链接:Angular2.0—路由跳转
- 父传子 —— 自定义属性
// news.html
//引入子组件,自定义属性
<app-zizujian [title]="title"></app-zizujian>
<a href="###" [routerLink]="['/news/child']" routerLinkActive='active' [queryParams]="{'id':1}">child</a>
//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
<p> zizujian works!</p>
<p> {{title}}</p>//渲染接收的值
// 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() {
}
}
- 子传父——自定义事件
//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<any>();
msg;
constructor() { }
ngOnInit() {
this.msg="我是子组件传给父组件的值"
}
send(){
// 发送事件,和参数
this.sends.emit(this.msg)
}
}
news.html
//监听事件sends
<app-zizujian (sends)=fu($event)></app-zizujian>
//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;
}
}
网友评论