Angular学习笔记(十七)父组件调用子组件数据

本文详细介绍了在Angular中如何通过ViewChild装饰器来实现父组件调用子组件的数据。通过示例代码展示了使用组件类名和模版本地变量作为参数的区别,并指出ViewChild用于获取单个匹配元素,而ViewChildren则用于获取匹配元素的集合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ViewChild

语法@ViewChild(ChildDirective) child: ChildDirective;

其中参数
- 类型:组件类名
- 字符串:包含模版本地变量的元素

demo —— 组件类名参数:

afterView.component.ts

export class AfterviewComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  greeting(name:string){
    console.log('hello,'+name);
  }

}

app.component.html

<app-afterview></app-afterview>

app.component.ts

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { StockInfo } from './child/child.component';
import { AfterviewComponent } from './afterview/afterview.component';

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

  @ViewChild(AfterviewComponent) greetdiv;

  ngOnInit(){
    this.greetdiv.greeting("Tom");
  }
}

控制台输出:hello,Tom

demo ——本地变量参数:
app.component.html

<app-afterview  #greet></app-afterview>

app.component.ts

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { StockInfo } from './child/child.component';
import { AfterviewComponent } from './afterview/afterview.component';

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

  @ViewChild('greet') greetdiv:AfterviewComponent ;

  ngOnInit(){
    this.greetdiv.greeting("Tom");
  }
}

区别:
@ViewChild(AfterviewComponent)可以获取组件为AfterviewComponent的参数
@ViewChild('greet')可以获取本地变量#greet

ViewChildren: ViewChildren返回一个集合,可以用this.greetdivs['first'].greeting("Tom"),ViewChild返回一个元素,匹配的第一个元素。

模版变量调用

app.component.html

<app-afterview  #greet2></app-afterview>
<button (click)="greet2.greeting('Jerry')">按钮</button>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值