Búsqueda de sitios web

javascript - Angular 4 @HostBinding('attr.id') no funciona (indefinido)


Tengo dificultades para vincularme al atributo 'id' del elemento host en mi directiva select-picker. Estoy usando @HostBinding('attr.id'), pero devuelve undefined. He revisado la documentación actual y parece que esta es la forma en que debería hacerse esta tarea simple.

Aquí está mi componente:

import {Component, OnInit, Input, Output, EventEmitter, AfterViewInit, HostBinding} from '@angular/core';
declare const $;

@Component({
    selector: '[select-picker]',
    templateUrl: 'select-picker.component.html'
})

export class SelectPickerComponent implements OnInit, AfterViewInit {

    @Input() options: Array<Object>;
    @Input() @HostBinding('class.cancelable') cancelable: boolean;
    @Input() @HostBinding('class.expand-up') expandUp: boolean;
    @Input() @HostBinding('style.width') elemWidth: string;
    @HostBinding('attr.id') id: string;

    @Output() value: EventEmitter<boolean> = new EventEmitter<boolean>();

    select: any;

    constructor() {
    }

    ngOnInit() {
        console.log(this.id) // <-- this logs 'undefined';
    }

    ngAfterViewInit() {
        const self = this;
        this.select = $(`#${this.id} select`).selectize({ // this init works, but with `id="undefined"`
            readOnly: true,
            onChange: function (val) {
                self.value.emit(val);
            },
            dropdownDirection: 'up'
        });
    }

    discardValue() {
        this.select[0].selectize.setValue(0);
    }
}

Y esta es la vista (desde el componente padre donde se usa la directiva):

<div select-picker id="page-options" [options]="pageOptions" [elemWidth]="'200px'" (value)="setItemsPerPage($event)"></div>

Respuesta #1

La vinculación de atributos para valores estáticos también se puede hacer de manera simple:

@Input() id: string;

Ambas versiones - <div id="some-static-id" ...> y <div [id]="someDynamicId" ...> - establecerán el valor en tu componente al usar @Input().

EDICIÓN: Sin embargo, se desaconseja encarecidamente usar jQuery y buscar por IDs en Angular. Yo cuestionaría si tu enfoque es la mejor opción para lograr lo que deseas. Probablemente deberías crear una pregunta separada donde expliques lo que intentas lograr y cuál es la mejor manera de hacerlo con Angular.

Respuesta #2

Podrías obtener directamente el valor del atributo de un elemento usando el método getAttribute en el DOM de la directiva. Esto solo funcionará cuando tengas un id de elemento estático. Si quieres pasar el id de forma dinámica, usa enlaces Input.

constructor(private elementRef: ElementRef){}
ngOnInit() {
    this.elementRef.nativeElement.getAttribute('id')
}

Demostración de Plunker

Artículos relacionados