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

我只是想知道如何在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或输入元素的引用?


当前回答

从列表中选择目标元素。从相同的元素列表中选择特定的元素是很容易的。

组件代码:

export class AppComponent {
  title = 'app';

  listEvents = [
    {'name':'item1', 'class': ''}, {'name':'item2', 'class': ''},
    {'name':'item3', 'class': ''}, {'name':'item4', 'class': ''}
  ];

  selectElement(item: string, value: number) {
    console.log("item="+item+" value="+value);
    if(this.listEvents[value].class == "") {
      this.listEvents[value].class='selected';
    } else {
      this.listEvents[value].class= '';
    }
  }
}

html代码:

<ul *ngFor="let event of listEvents; let i = index">
   <li  (click)="selectElement(event.name, i)" [class]="event.class">
  {{ event.name }}
</li>

css代码:

.selected {
  color: red;
  background:blue;
}

其他回答

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

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

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

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

HTML代码:

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

TS代码:

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

class TemplateFormComponent {

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

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

快速使用的最小示例:

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攻击

对于*ngIf中的组件,另一种方法是:

我想要选择的组件是在一个div的*ngIf语句中,@ jsgopil的答案上面可能工作(谢谢@ jsgopil !),但我最终找到了一种避免使用*ngIf的方法,通过使用CSS隐藏元素。

当[className]中的条件为真时,将显示div,使用#命名组件可以工作,并且可以从typescript代码中选择它。当条件为false时,它不会显示,而且我不需要选择它。

组件:

@Component({
    selector: 'bla',
    templateUrl: 'bla.component.html',
    styleUrls: ['bla.component.scss']
})
export class BlaComponent implements OnInit, OnDestroy {
    @ViewChild('myComponentWidget', {static: true}) public myComponentWidget: any;
    @Input('action') action: ActionType; // an enum defined in our code. (action could also be declared locally)

constructor() {
   etc;
}

// this lets you use an enum in the HMTL (ActionType.SomeType)
public get actionTypeEnum(): typeOf ActionType {
    return ActionType;
}

public someMethodXYZ: void {
    this.myComponentWidget.someMethod(); // use it like that, assuming the method exists
}

然后在bla。component.html文件中:

<div [className]="action === actionTypeEnum.SomeType ? 'show-it' : 'do-not-show'">

    <my-component #myComponentWidget etc></my-component>
</div>
<div>
    <button type="reset" class="bunch-of-classes" (click)="someMethodXYZ()">
        <span>XYZ</span>
    </button>
</div>   

和CSS文件:

 ::ng-deep {
    .show-it {
         display: block;   // example, actually a lot more css in our code
    }
    .do-not-show {
        display: none'; 
    }
}

注意:这并不适用于Angular 6及以上版本,因为ElementRef变成了ElementRef<T>, T表示nativeElement的类型。

我想补充一点,如果您正在使用ElementRef,正如所有答案所推荐的那样,那么您将立即遇到一个问题,即ElementRef有一个看起来很糟糕的类型声明

export declare class ElementRef {
  nativeElement: any;
}

这在一个nativeElement是HTMLElement的浏览器环境中是愚蠢的。

要解决这个问题,您可以使用以下技术

import {Inject, ElementRef as ErrorProneElementRef} from '@angular/core';

interface ElementRef {
  nativeElement: HTMLElement;
}

@Component({...}) export class MyComponent {
  constructor(@Inject(ErrorProneElementRef) readonly elementRef: ElementRef) { }
}