当前位置: 首页 > news >正文

[Angular] 笔记 21:@ViewChild

chatgpt:
在 Angular 中,@ViewChild 是一个装饰器,用于在组件类中获取对模板中子元素、指令或组件的引用。它允许你在组件类中访问模板中的特定元素,以便可以直接操作或与其交互。

例如,如果你在模板中有一个子组件或一个具有本地引用的元素,你可以使用 @ViewChild 装饰器在组件类中获取对该元素的引用。这样,你就可以在组件类中调用该元素的方法、访问其属性或者订阅其事件。

这是一个简单的示例,演示了如何在 Angular 组件中使用 @ViewChild

import { Component, ViewChild, ElementRef } from '@angular/core';@Component({selector: 'app-example',template: `<div #myElement>Some content</div>`
})
export class ExampleComponent {@ViewChild('myElement', { static: true }) myElementRef: ElementRef;ngAfterViewInit() {// 可以在这里访问和操作子元素console.log(this.myElementRef.nativeElement.textContent); // 获取子元素的文本内容this.myElementRef.nativeElement.style.color = 'red'; // 修改子元素的样式}
}

在这个例子中,@ViewChild 装饰器用于获取模板中带有 #myElement 本地引用的 <div> 元素的引用,并在 ngAfterViewInit 生命周期钩子中对其进行操作。

需要注意的是,@ViewChild 装饰器接受一个选择器作为参数,用于定位模板中的元素。在这里,我们使用了 #myElement 选择器来获取对应的元素引用。

另外,{ static: true }@ViewChild 的一个配置选项,用于指定何时应该去查询视图中的元素。{ static: true } 表示在组件初始化时就会进行查询,{ static: false } 表示在首次调用 ngAfterViewInit 生命周期钩子时进行查询。


Angular For Beginners - 25. @ViewChild()

当使用 JavaScript 时,可以使用 getElementById 来获取特定的 HTML 元素对象。但在 Angular 中,并没有类似于 getElementById 的直接函数。相反,Angular 提供了 @ViewChild 这样的装饰器,用于在组件类中获取模板中特定元素的引用,从而实现类似的功能。

在这里插入图片描述

但是,getElementById 的参数与 @ViewChild 的参数有很大的不同。 不能传 html 标签或 css 选择器给 @ViewChild,传进 @ViewChild 中的参数分以下 4 种:

在这里插入图片描述

在这里插入图片描述

1.

pokemon-list.compoment.html 增加一个 template ref #pokemonRef:

<table><thead><th>Name</th><th>Index</th></thead><tbody><app-pokemon-detail#pokemonRef     // new code*ngFor="let pokemon of pokemons"[detail]="pokemon"(remove)="handleRemove($event)"><h1>-----------------------</h1><h2>============================</h2><h3></h3></app-pokemon-detail></tbody>
</table>

2.

多个孩子用 @ViewChildren ,单个用 @ViewChild

@ViewChild 只能在 View 渲染之后才能使用:

在这里插入图片描述

pokemon-list.compoment.ts :

因为 ngAfterViewInit 继承了 AfterViewInit, 所以 PokemonListComponent 需要 implement AfterViewInit:

export class PokemonListComponent implements OnInit, AfterViewInit {

完整代码如下:

import { AfterViewInit, Component, ElementRef, OnInit, ViewChild, ViewChildren } from '@angular/core';
import { Pokemon } from 'src/app/models/pokemon';
import { PokemonService } from 'src/app/services/pokemon.service';@Component({selector: 'app-pokemon-list',templateUrl: './pokemon-list.component.html',styleUrls: ['./pokemon-list.component.css'],
})
export class PokemonListComponent implements OnInit, AfterViewInit {// pokemons!: Pokemon[];pokemons: Pokemon[] = [];// 这里不是 @ViewChild, 否则log 为 undefined// 而是 @ViewChildren,使用了 for 循环, 孩子数多于一个,有3个。@ViewChildren('pokemonRef') pokemonRef!: ElementRef;constructor(private pokemonService: PokemonService) {}// 新代码ngAfterViewInit(): void {// throw new Error('Method not implemented.');console.log("ngAfterViewInit begin")console.log(this.pokemonRef)console.log("ngAfterViewInit end")}handleRemove(event: Pokemon) {this.pokemons = this.pokemons.filter((pokemon: Pokemon) => {return pokemon.id !== event.id;});}ngOnInit(): void {// 填充 pokemons 属性// this.pokemons = this.pokemonService.getPokemons();this.pokemonService.getPokemons().subscribe((data: Pokemon[]) => {console.log(data);this.pokemons = data;});}
}

3. web 页面:

在这里插入图片描述

相关文章:

  • Python编程技巧 – format格式化文本
  • 10、python-装饰器
  • vscode中默认shell选择
  • VCG 基于CMake构建VCG项目
  • 基于STM/APM32F072制作的J-Link OB调试器项目验证
  • 使用webdriver-manager解决浏览器与驱动不匹配所带来自动化无法执行的问题
  • 劫持最新版 QQNT / QQ / TIM 客户端 ClientKeys
  • 第十章 创建Callout Library - 使用 B 链接类型传递短计数字符串
  • MySQL的事务隔离级别
  • LeetCode 394:字符串解码
  • latexshop 使用bug:xxx has a comma at the end
  • 子网掩码与IP段计算
  • java企业网站系统Myeclipse开发mysql数据库web结构java编程计算机网页项目
  • PAT 乙级 1042 字符统计
  • 无需手动搜索!轻松创建IntelliJ IDEA快捷方式的Linux教程
  • angular学习第一篇-----环境搭建
  • C++类的相互关联
  • Druid 在有赞的实践
  • ESLint简单操作
  • export和import的用法总结
  • input的行数自动增减
  • Material Design
  • mongodb--安装和初步使用教程
  • Python_OOP
  • Spring Cloud Alibaba迁移指南(一):一行代码从 Hystrix 迁移到 Sentinel
  • UMLCHINA 首席专家潘加宇鼎力推荐
  • 等保2.0 | 几维安全发布等保检测、等保加固专版 加速企业等保合规
  • 官方新出的 Kotlin 扩展库 KTX,到底帮你干了什么?
  • 记一次删除Git记录中的大文件的过程
  • 京东美团研发面经
  • 模仿 Go Sort 排序接口实现的自定义排序
  • 我看到的前端
  • ionic入门之数据绑定显示-1
  • ​iOS实时查看App运行日志
  • ​七周四次课(5月9日)iptables filter表案例、iptables nat表应用
  • ​软考-高级-系统架构设计师教程(清华第2版)【第9章 软件可靠性基础知识(P320~344)-思维导图】​
  • #14vue3生成表单并跳转到外部地址的方式
  • #我与Java虚拟机的故事#连载09:面试大厂逃不过的JVM
  • (003)SlickEdit Unity的补全
  • (AngularJS)Angular 控制器之间通信初探
  • (floyd+补集) poj 3275
  • (Java数据结构)ArrayList
  • (pojstep1.1.2)2654(直叙式模拟)
  • (ZT)北大教授朱青生给学生的一封信:大学,更是一个科学的保证
  • (二十三)Flask之高频面试点
  • (黑马出品_高级篇_01)SpringCloud+RabbitMQ+Docker+Redis+搜索+分布式
  • (未解决)jmeter报错之“请在微信客户端打开链接”
  • (转)visual stdio 书签功能介绍
  • (转)编辑寄语:因为爱心,所以美丽
  • (转)创业的注意事项
  • (转)我也是一只IT小小鸟
  • (转载)Linux网络编程入门
  • .net core 客户端缓存、服务器端响应缓存、服务器内存缓存
  • .NET Framework与.NET Framework SDK有什么不同?
  • .NET Standard 支持的 .NET Framework 和 .NET Core