有人知道如何获取组件模板中定义的元素吗?聚合物让$和$$变得很容易。

我只是想知道如何在Angular中实现它。

以教程中的例子为例:

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;
    }
}

我如何从类定义中捕获或获得p或输入元素的引用?


当前回答

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) {
    // ...
  }
}

示例已更新以使用最新版本

有关本机元素的更多详细信息,请点击这里

其他回答

要获得紧邻的下一个兄弟姐妹,使用这个

event.source._elementRef.nativeElement.nextElementSibling

对于那些试图在*ngIf或*ngSwitchCase中获取组件实例的人,你可以遵循这个技巧。

创建一个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);
    }
}

导出名称为myComponent的组件

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

使用这个模板获取ElementRef和MyComponent实例

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

在TypeScript中使用此代码

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

快速使用的最小示例:

import { Component, ElementRef, ViewChild} from '@angular/core';

@Component({
  selector: 'my-app',
  template:
  `
  <input #inputEl value="hithere">
  `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild('inputEl') inputEl:ElementRef; 

  ngAfterViewInit() {
    console.log(this.inputEl);
  }
}

在感兴趣的DOM元素上放置一个模板引用变量。在我们的例子中,这是<input>标签上的#inputEl。 在组件类中,通过@ViewChild装饰器注入DOM元素 访问ngAfterViewInit生命周期钩子中的元素。

注意:

如果你想操作DOM元素,请使用Renderer2 API而不是直接访问元素。允许直接访问DOM会使应用程序更容易受到XSS攻击

从@angular/core中导入ViewChild装饰器,如下所示:

HTML代码:

<form #f="ngForm"> 
  ... 
  ... 
</form>

TS代码:

import { ViewChild } from '@angular/core';

class TemplateFormComponent {

  @ViewChild('f') myForm: any;
    .
    .
    .
}

现在你可以使用'myForm'对象来访问类中的任何元素。

你可以通过ElementRef将DOM元素的句柄注入到组件的构造函数中:

constructor(private myElement: ElementRef) { ... }

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