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

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


当前回答

我用了两种方法:

第一种方法:

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

constructor(private myElement: ElementRef) {
this.myElement.nativeElement // <- your direct element reference
}

第二种方式:

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

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

其他回答

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

event.source._elementRef.nativeElement.nextElementSibling

对于*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 Material,你可以利用cdkFocusInitial指令。

示例:<input matInput cdkFocusInitial>

点击此处阅读更多信息: https://material.angular.io/cdk/a11y/overview#regions

对于那些试图在*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) {
}

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

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

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