home.component.ts

import { Component, OnInit } from '@angular/core'; @Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit { constructor() { } ngOnInit() {
} app_substring: string = "<app-subcomponet [msg]='msg' [parentFun]='parentFun'></app-subcomponet>";
app_substringtwo:string="在parent.component的模板中使用 <app-subcomponet (childbroadcastevent)=parentsubcribe($event)"; }
header.component.html

<!-- <p>header works!</p> -->
<h1 class="header">this is {{msg}}</h1>
<hr />
<button (click)='childFun()'>调用父组件的方法</button>
<button (click)='childOutFun()'>子组件广播事件向父组件传值</button>
<hr />
<!-- ----------------header data--------------------
{{title}}---{{msg}} -->
header.component.ts

import { Component, OnInit, Input, OnDestroy, OnChanges, Output, EventEmitter } from '@angular/core';
// import { EventEmitter } from 'protractor'; @Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit, OnDestroy, OnChanges {
title = 'this is header\'s title'; //模板参数定义方式,注意,input传入的是对象,即可以是属性,还可以是方法 ///接收父组件的属性
@Input() msg: string; @Input() parentFun: any; @Output() childOut = new EventEmitter<string>(); message: string; constructor() {
console.log('constructor...' + this.msg);
} ngOnInit() {
// this.msg = 'this is header data'
console.log('ngOnInit...' + this.msg);
} ngOnDestroy() {
console.log('ngOnDestroy...' + this.msg);
} ngOnChanges() {
console.log('ngOnChanges...' + this.msg);
} childFun() {
this.message = '这是header传给父组件的参数';
this.parentFun(this.message);
} ///子组件定义一个output的属性,来作为父组件的引用,进行广播
///父组件通过,监听这样一个子组件的广播属性,来响应子组件的操作 注意:由于是事件,所以用 ()
childOutFun() {
this.childOut.emit('子组件向父组件广播的emitdata');
} childFunForParent() {
alert('供父组件调用的方法');
}
}
news.component.ts

import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { HttpClient } from '@angular/common/http'; @Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit, AfterViewInit {
@ViewChild('headerchild', { read: '', static: true }) headerchild;
public news: any[];
protected spanhtml: string = '<h2>测试显示HTML代码,是否能解析成功</h2>';
protected id: Number = 100; public search: string = '';
public msg: string = '这是news的Header'; constructor(private http: HttpClient) {
this.news = [
{
'cateName': '宝马',
'brand': [{ 'title': '宝马X1' },
{ 'title': '宝马X1' },
{ 'title': '宝马X2' },
{ 'title': '宝马X3' },
{ 'title': '宝马X4' }]
},
{
'cateName': '奥迪',
'brand': [{ 'title': '奥迪q1' },
{ 'title': '奥迪q2' },
{ 'title': '奥迪q3' },
{ 'title': '奥迪q4' },
{ 'title': '奥迪q5' }]
},
{
'cateName': '中华',
'brand': []
}
];
}
ngOnInit() {
} ngAfterViewInit() { } getApiData() {
let url: string = 'https://itunes.apple.com/search';
let searchUrl = `${url}?term=${this.search}&media=music&limit=20`;
this.http.jsonp(url, 'callback').subscribe(
function (data) { console.log(data) },
function (error) { console.log(error) })
} ///父组件通过属性传值公开给子组件的方法
parentFun(msg) {
alert(msg);
} ///父组件监听的子组件方法
parentAimedFun(e) {
alert(e);
} ////父组件通过viewchild直接调用子组件的方法
excuteChildFunByViewChild() {
this.headerchild.childFunForParent();
} }
news.component.html

<app-header [msg]='msg' [parentFun]='parentFun' (childOut)='parentAimedFun($event)' #headerchild></app-header>

<button (click)="headerchild.childFunForParent()">试试父组件执行子组件方法</button>
<button (click)="excuteChildFunByViewChild()">试试父组件通过viewchild执行子组件方法</button> <br>
<p>news works!</p>
<span [innerHTML]="spanhtml"></span>
<div [id]="id"></div> <div>
<ul>
<li *ngFor="let item of news;let key=index">
系列:{{item.cateName}}<br>
车型数量:{{item.brand.length}}
<ol>
<div *ngIf="item.brand.length>0">
<li *ngFor="let car of item.brand;let key=index">
车型:{{car.title}}
</li>
</div>
<div *ngIf="item.brand.length==0">
暂无更多数据
</div>
</ol>
</li>
</ul>
</div> <hr />
<h2>Jsonp查询数据</h2>
输入关键字:<input type="text" [(ngModel)]="search" />
<button (click)="getApiData()">点击查询</button>
 
父组件向子组件传值的方法:
<br>
1.通过对子组件的引用,给子组件绑定 属性,如
<div>{{app_substring}}</div>
<br>
其中:msg parentFun 都是 父组件给子组件绑定的属性
<br>
子组件通过@input() 属性名:type(类型 不知道则为any)来获取
父组件的属性传值
<br />
例如:<br />
@Input() msg: string;<br />
@Input() parentFun: any;
2.关于output的用法
output是和eventemitter一起使用来实现父子组件传值的
原理:
a 子组件进行事件广播
b 父组件在引用的子组件时,监听广播事件,既然是事件,那么写法肯定是(事件名称)='父组件的事件函数()'
<div>{{app_substringtwo}}</div>
app-subcomponet的childbroadcastevent为:
@output() childbroadcastevent=new EventEmitter<T>() 注意:T即为传播的数据类型
childOutEvent(){
this.childbroadcastevent.emit('some data to parent');
}
即发布订阅模式,来实现值的传输
当子组件的某个操作触发childOutEvent的时候,函数调用:childbroadcastevent 广播事件,而父组件监听这个事件
所以就可以接受来自子组件的数据
3.使用viewchild
父组件申明 @viewchild('子组件的selector') 这时候,相当于拿到子组件的实例,然后就可以直接调用子组件的方法或者使用子组件的属性了
可以理解为代理模式

angular 4+中关于父子组件传值的示例的更多相关文章

  1. Angular 父子组件传值

    Angular 父子组件传值 @Input  @Output  @ViewChild 新建一个头部组件 newsheader 在主组件引用 news 组件,在news组件添加 newsheader 组 ...

  2. 关于element中的父子组件的传值问题

    首先讲一下父子组件的传值问题. 这是大家很熟悉的一张图,讲述了父子组件传值的过程.父组件通过prop传值给子组件,子组件通过$emit给父组件发送消息来使父组件的prop发生变化.这都是老生常谈了.下 ...

  3. 十八、React react-router4.x中:实现路由模块化、以及嵌套路由父子组件传值

    一.路由模块化(用字典定义路由,然后循环出来) 1.官方文档参考 [官方文档]https://reacttraining.com/react-router/web/guides/quick-start ...

  4. 使用react进行父子组件传值

    在单页面里面,父子组件传值是比较常见的,之前一直用vue开发,今天研究了一下react的父子组件传值,和vue差不多的思路,父组件向子组件传值,父通过初始state,子组件通过this.props进行 ...

  5. 【vue】父组件主动调用子组件 /// 非父子组件传值

    一  父组件主动调用子组件: 注意:在父组件使用子组件的标签上注入ref属性,例如: <div id="home"> <v-header ref="he ...

  6. vue父子组件传值加例子

    例子:http://element-cn.eleme.io/#/zh-CN/component/form         上进行改的 父传子:用prop:子组件能够改变父组件的值,是共享的,和父操作是 ...

  7. angularJS中directive父子组件的数据交互

    angularJS中directive父子组件的数据交互 1. 使用共享 scope 的时候,可以直接从父 scope 中共享属性.使用隔离 scope 的时候,无法从父 scope 中共享属性.在 ...

  8. Vue中非父子组件传值的问题

    父子组件传值的问题,前面已经讲过,不再叙述,这里来说一种非父子组件的传值. vue官网指出,可以使用一个空vue实例作为事件中央线! 也就是说 非父子组件之间的通信,必须要有公共的实例(可以是空的), ...

  9. 创建组件的方法,组件的props属性、state属性的用法和特点,父子组件传值,兄弟组件传值

    1.创建组件的方法   函数组件   class组件 1.1 函数组 无状态函数式组件形式上表现为一个只带有一个 `render()` 方法的组件类,通过函数形式或者 `ES6` 箭头 `functi ...

随机推荐

  1. C++入门经典-例7.3-析构函数的调用

    1:析构函数的名称标识符就是在类名标识符前面加“~”.例如: ~CPerson(); 2:实例代码: (1)title.h #include <string>//title是一个类,此为构 ...

  2. 石川es6课程---11、json

    石川es6课程---11.json 一.总结 一句话总结: ` 感觉更方便了一点,增加了一些简写 ` key-value 一样时可以简写:console.log({ a,b}}) ` 里面函数可以简写 ...

  3. python中列表的简单用法

    1.定义list >>> li = ["a", "b", "mpilgrim", "z", " ...

  4. jstack+jdb命令查看线程及死锁堆栈信息

    如果程序挂死,有时使用jstack查看进程中线程信息时,需要添加上-F参数,此时如果有死锁信息,则可能不会打印出死锁堆栈信息,使用jdb则可以查看当前死锁线程的运行堆栈. 如下模拟一个简单的死锁程序 ...

  5. mysql 存储过程中使用动态sql语句

    Mysql 5.0 以后,支持了动态sql语句,我们可以通过传递不同的参数得到我们想要的值 这里介绍两种在存储过程中的动态sql: set sql = (预处理的sql语句,可以是用concat拼接的 ...

  6. zipkin-client:brave核心代码思路整理

    Zipkin是分布式跟踪系统. 简单地理解,可以将Zipkin分为两部分. 一部分为Zipkin Server,其负责接受存储应用程序处理耗时数据,以及UI展示. 另一部分为Zipkin Client ...

  7. Springboot2.0实现URL拦截

    1.创建一个登陆拦截器SecurityInterceptor,它继承HandlerInterceptorAdapter类 package com.cn.commodity.config; import ...

  8. WPF使用cefsharp 下载地址

    源码下载: https://github.com/cefsharp/CefSharp dll类库包下载nuget: https://www.nuget.org/packages/CefSharp.Wp ...

  9. Java异常超详细总结

    1.1,什么是异常:   异常就是Java程序在运行过程中出现的错误. 骚话: 世界上最真情的相依就是你在try我在catch,无论你发什么脾气,我都静静接受,默默处理(这个可以不记) 1.2,异常继 ...

  10. k8s1.11.0安装、一个master、一个node、查看node名称是ip、node是扩容进来的、带cadvisor监控服务

    一个master.一个node.查看node节点是ip # 安装顺序:先在test1 上安装完必要组件后,就开始在 test2 上单独安装node组件,实现node功能,再返回来配置test1加入集群 ...