发表于: 2020-06-11 22:42:05

1 2220


今天完成的事情:今天学习了一下父组件调用子组件的方法以及通信
明天计划的事情:继续后续的学习
遇到的问题:自己动手尝试了几次总是有奇怪的报错一会又有自己好了,没搞清楚还是要多做几次
收获:组件是一种特殊的指令,使用更简单的配置项来构建基于组件的应用程序架构

应用组件的优点:

  • 比普通指令配置还简单
  • 提供更好的默认设置和最好的实践
  • 对基于组建的应用架构更优化。
  • 对angular的升级更平滑。

不用组建的情况:

  • 对那些在 compile或者pre-link阶段要执行操作的指令,组件不能用,因为无法到达那个阶段。
  • 如果你想定义指令的  priority,terminal,multi-element,也不能用。
  • 组件只能通过元素标签触发,其他的只能用命令。

viewChild装饰器。

父组件的模版和控制器里调用子组件的API。

import { ComponentOnInit } from '@angular/core';
@Component({
 selector: 'app-child1',
 templateUrl: './child1.component.html',
 styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit {
 constructor() { }
 ngOnInit() {
 }
 greeting(namestring) {
 console.log("hello" + name);
 }
}

2、父组件中分别在模版中用模版本地变量调用和在控制器中用ts代码调用。

父组件写2个<app-child>并分别指定模版本地变量

<app-child1 #child1> </app-child1>
<app-child1 #child2> </app-child1>

3,在父组件控制器中声明一个由viewChild装饰器装饰的变量获得子组件的引用。

通过模版变量的名字child1找到相应的子组件并赋值给child1变量,拿到引用就可以调用子组件方法。

@ViewChild('child1')
child1:Child1Component//父组件中获得子组件的引用
ngOnInit(){
 this.child1.greeting("Tom");
}


4,在父组件模版中调用子组件方法。

在父组件模版中加一个button,点击时去调用子组件child2的greeting方法。

<app-child1 #child1> </app-child1>
<app-child1 #child2> </app-child1>
<button (click)="child2.greeting('Jerry')">调用child2的greeting方法</button>

虽然自己做最后成功了但是中途总出现一下莫名的报错一会又好了,明天再继续研究一下

组件通信的话有以下几种典型的通讯方案:

直接的父子关系:父组件直接访问子组件的 public 属性和方法。

直接的父子关系:借助于 @Input 和 @Output 进行通讯

没有直接关系:借助于 Service 单例进行通讯。

利用 cookie 和 localstorage 进行通讯。

利用 session 进行通讯。

父子通信:Input Down

  1. 父组件通过子组件标签传递属性
  2. 子组件在内部声明 @Input 接收

     3.Input 是单向的

  • 父组件如果把数据改了,子组件也会更新
  • 但是反之不会
  • 有一个例外,引用类型修改

子组件:

import { ComponentInput } from '@angular/core';
 
import { Hero } from './hero';
 
@Component({
  selector: 'app-hero-child',
  template: `
    <h3>{{hero.name}} says:</h3>
    <p>I, {{hero.name}}, am at your service, {{masterName}}.</p>
  `
})
export class HeroChildComponent {
  // 声明接收父组件传递的数据
  @Input() heroHero;
  @Input('master'masterNamestring// 接收 master 重命名为 masterName


父组件:

import { Component } from '@angular/core';
 
import { HEROES } from './hero';
 
@Component({
  selector: 'app-hero-parent',
  template: `
    <h2>{{master}} controls {{heroes.length}} heroes</h2>
    <!-- 在子组件标签上传递数据 -->
    <app-hero-child *ngFor="let hero of heroes"
      [hero]="hero"
      [master]="master">
    </app-hero-child>
  `
})
export class HeroParentComponent {
  heroes = HEROES;
  master = 'Master';

其他的方法还没看明白明天再继续进行


返回列表 返回列表
评论

    分享到