本文翻译自:How can I select an element in a component template?

Does anybody know how to get hold of an element defined in a component template? 有人知道如何掌握组件模板中定义的元素吗? Polymer makes it really easy with the $ and $$ . 使用$$$可以使Polymer变得非常容易。

I was just wondering how to go about it in Angular. 我只是想知道如何在Angular中进行操作。

Take the example from the tutorial: 从教程中获取示例:

import {Component} from '@angular/core'@Component({selector:'display'template:`<input #myname(input)="updateName(myname.value)"/><p>My name : {{myName}}</p>`})
export class DisplayComponent {myName: string = "Aman";updateName(input: String) {this.myName = input;}
}

How do I catch hold of a reference of the p or input element from within the class definition? 如何从类定义中抓住对pinput元素的引用?


#1楼

参考:https://stackoom.com/question/2DAxR/如何在组件模板中选择元素


#2楼

You can get a handle to the DOM element via ElementRef by injecting it into your component's constructor: 您可以通过将ElementRef注入到组件的构造函数中来通过ElementRef获取DOM元素的句柄:

constructor(myElement: ElementRef) { ... }

Docs: https://angular.io/docs/ts/latest/api/core/index/ElementRef-class.html 文件: https : //angular.io/docs/ts/latest/api/core/index/ElementRef-class.html


#3楼

import { Component, ElementRef, OnInit } from '@angular/core';@Component({selector:'display',template:`<input (input)="updateName($event.target.value)"><p> My name : {{ myName }}</p>`
})
class DisplayComponent implements OnInit {constructor(public element: ElementRef) {this.element.nativeElement // <- your direct element reference }ngOnInit() {var el = this.element.nativeElement;console.log(el);}updateName(value) {// ...}
}

Example updated to work with the latest version 示例已更新以使用最新版本

For more details on native element, here 有关本机元素的更多详细信息,请单击此处


#4楼

Instead of injecting ElementRef and using querySelector or similar from there, a declarative way can be used instead to access elements in the view directly: 代替注入ElementRef并从那里使用querySelector或类似的方法,可以使用声明性方法直接访问视图中的元素:

<input #myname>
@ViewChild('myname') input;

element 元件

ngAfterViewInit() {console.log(this.input.nativeElement.value);
}

StackBlitz example StackBlitz示例

  • @ViewChild() supports directive or component type as parameter, or the name (string) of a template variable. @ViewChild()支持将指令或组件类型作为参数,或模板变量的名称(字符串)。
  • @ViewChildren() also supports a list of names as comma separated list (currently no spaces allowed @ViewChildren('var1,var2,var3') ). @ViewChildren()还支持以逗号分隔列表的名称列表(当前不允许使用空格@ViewChildren('var1,var2,var3') )。
  • @ContentChild() and @ContentChildren() do the same but in the light DOM ( <ng-content> projected elements). @ContentChild()和@ContentChildren()的功能相同,但使用的是DOM( <ng-content>投影元素)。

descendants 子孙

@ContentChildren() is the only one that allows to also query for descendants @ContentChildren()是唯一一个还可以查询后代的人

@ContentChildren(SomeTypeOrVarName, {descendants: true}) someField;

{descendants: true} should be the default but is not in 2.0.0 final and it's considered a bug {descendants: true}应该是默认值,但不在2.0.0 final中,因此 被认为是错误
This was fixed in 2.0.1 此问题已在2.0.1中修复

read

If there are a component and directives the read parameter allows to specify which instance should be returned. 如果有组件和指令,则read参数允许指定应返回哪个实例。

For example ViewContainerRef that is required by dynamically created components instead of the default ElementRef 例如,动态创建的组件而不是默认的ElementRef需要ViewContainerRef

@ViewChild('myname', { read: ViewContainerRef }) target;

subscribe changes 订阅更改

Even though view children are only set when ngAfterViewInit() is called and content children are only set when ngAfterContentInit() is called, if you want to subscribe to changes of the query result, it should be done in ngOnInit() 即使仅在ngAfterViewInit()时才设置视图子级,而仅在ngAfterViewInit()时才设置内容子级, ngAfterContentInit() ,如果要订阅查询结果的更改,则应在ngOnInit()

https://github.com/angular/angular/issues/9689#issuecomment-229247134 https://github.com/angular/angular/issues/9689#issuecomment-229247134

@ViewChildren(SomeType) viewChildren;
@ContentChildren(SomeType) contentChildren;ngOnInit() {this.viewChildren.changes.subscribe(changes => console.log(changes));this.contentChildren.changes.subscribe(changes => console.log(changes));
}

direct DOM access 直接DOM访问

can only query DOM elements, but not components or directive instances: 只能查询DOM元素,而不能查询组件或指令实例:

export class MyComponent {constructor(private elRef:ElementRef) {}ngAfterViewInit() {var div = this.elRef.nativeElement.querySelector('div');console.log(div);}// for transcluded contentngAfterContentInit() {var div = this.elRef.nativeElement.querySelector('div');console.log(div);}
}

get arbitrary projected content 获得任意的投影内容

See Access transcluded content 请参阅访问包含的内容


#5楼

For people trying to grab the component instance inside a *ngIf or *ngSwitchCase , you can follow this trick. 对于试图在*ngIf*ngSwitchCase获取组件实例的*ngSwitchCase ,您可以按照以下技巧进行操作。

Create an init directive. 创建一个init指令。

import {Directive,EventEmitter,Output,OnInit,ElementRef
} from '@angular/core';@Directive({selector: '[init]'
})
export class InitDirective implements OnInit {constructor(private ref: ElementRef) {}@Output() init: EventEmitter<ElementRef> = new EventEmitter<ElementRef>();ngOnInit() {this.init.emit(this.ref);}
}

Export your component with a name such as myComponent 使用诸如myComponent的名称导出组件

@Component({selector: 'wm-my-component',templateUrl: 'my-component.component.html',styleUrls: ['my-component.component.css'],exportAs: 'myComponent'
})
export class MyComponent { ... }

Use this template to get the ElementRef AND MyComponent instance 使用此模板获取ElementRef AND MyComponent实例

<div [ngSwitch]="type"><wm-my-component#myComponent="myComponent"*ngSwitchCase="Type.MyType"(init)="init($event, myComponent)"></wm-my-component>
</div>

Use this code in TypeScript 在TypeScript中使用此代码

init(myComponentRef: ElementRef, myComponent: MyComponent) {
}

#6楼

 */
import {Component,ViewChild} from '@angular/core' /*Import View Child*/@Component({selector:'display'template:`<input #myname (input) = "updateName(myname.value)"/><p> My name : {{myName}}</p>`
})
export class DisplayComponent{@ViewChild('myname')inputTxt:ElementRef; /*create a view child*/myName: string;updateName: Function;constructor(){this.myName = "Aman";this.updateName = function(input: String){this.inputTxt.nativeElement.value=this.myName; /*assign to it the value*/};}
}

如何在组件模板中选择元素?相关推荐

  1. d3.js中选择元素和绑定数据

    回顾一下如何选择元素 在 D3 中,用于选择元素的函数有两个: d3.select():是选择所有指定元素的第一个 d3.selectAll():是选择指定元素的全部 这两个函数返回的结果称为选择集. ...

  2. 解决laytpl.js模板引擎插件加载模板后无法获取模板中的元素id等内容

    一.问题描述 在页面中使用laytpl.js模板引擎,在页面加载后无法使用jquery获取模板中的html元素,以下是图片和代码: 在添加或修改完毕后重新加载页面,不能使用jquery获取模板中的ht ...

  3. 给 ListBox 的 DataTemplate 模板中的 元素设置动画

    首先定义模板: <DataTemplate x:Key="ItemTemplate"><Grid Width="470" Margin=&qu ...

  4. Tapestry 5 组件模板

    Tapestry 5 组件模板 本文根据http://tapestry.apache.org/tapestry5/tapestry-core/guide/templates.html翻译整理过来,请高 ...

  5. jQuery learn - 1 - 选择元素 CSS

    2019独角兽企业重金招聘Python工程师标准>>> CDN=Content Delivery Networks DOM=Document Object Model W3C=Wor ...

  6. 将选择元素绑定到Angular中的对象

    本文翻译自:Binding select element to object in Angular I'd like to bind a select element to a list of obj ...

  7. [vue] vue为什么要求组件模板只能有一个根元素?

    [vue] vue为什么要求组件模板只能有一个根元素? '为什么只能有且只有一个根元素'于是我花了二十多分钟去找了一下答案......竟然没有找到答案....好的现在我来说说我的理解,如果有不对的地方 ...

  8. vue学习-v-if v-for优先级、data、key、diff算法、vue组件化、vue设计原则、组件模板只有一个根元素、MVC.MVP,MVVM

    1:v-if和v-for哪个优先级更高?如果两个同时出现,应该怎么优化得到更好的性能? //在vue页面中 同时使用v-for与v-if后,打印渲染函数. console.log(app.$optio ...

  9. 《十》微信小程序中自定义组件的组件模板和样式

    组件 WXML 模板: 组件模板的写法与页面模板相同. 模板数据绑定: 与普通的 WXML 模板类似,可以使用数据绑定. <!-- custom-component.wxml --> &l ...

最新文章

  1. SunlightChain 区块链宣言
  2. python获取系统时间函数_Python常用时间操作总结【取得当前时间、时间函数、应用等】...
  3. java多线程 -- 创建线程的第三者方式 实现Callable接口
  4. 将 Citavi 笔记按需要导出
  5. 论文浅尝 - AAAI2020 | 小样本知识图谱补全
  6. 这就是程序员被大厂偏爱的实力!
  7. jquery选择器详解
  8. 在线教育平台源码组成概述
  9. python的金融计算器_Python计算器
  10. 【教程】CoreAVC+Haali安装及设置简易教程(KMPlayer)(1)
  11. 机械臂手眼标定原理及代码
  12. 字节跳动《Vim 中文手册》火了,完整版 PDF 开放下载!
  13. html5如何实现语音点歌,怎么给手机点歌 怎么样用自己手机给对方手机点歌
  14. jquery实现页面等待加载“转圈圈”效果
  15. 苹果xr如何关机_苹果新系统让这些 iPhone 电量满血复活
  16. C#读取Excel数据在CAD上展图
  17. BI 到底是什么,看看这篇文章怎么说
  18. C语言中 指针变量 取地址符的用法 *指针变量名的用法
  19. 【源码】基于心电图的数据分析
  20. 最小二乘拟合多项式(利用构造正交多项式的方法)C++

热门文章

  1. LiteRouter 路由
  2. openfire 插件开发
  3. IOS开发笔记5-C语言基础复习
  4. 创建型模式--单例模式
  5. Scroller解析
  6. python软件在下载库文件_python – 并行下载多个文件的库或工具
  7. 微信小程序ios可以上下左右拖动的问题
  8. [poj3041]Asteroids(二分图的最小顶点覆盖)
  9. 《大话设计模式》--代理模式
  10. Cocos2d-x Touch事件处理机制