最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 4 @HostBinding('attr.id') does not work (undefined) - Stack Overflow

programmeradmin0浏览0评论

I have difficulties binding to host element 'id' attribute in my select-picker directive. I am using @HostBinding('attr.id'), but it returns undefined. I have checked the actual DOC and it looks like this is the way this simple task should be done.

Here is my ponent:

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

@Component({
    selector: '[select-picker]',
    templateUrl: 'select-pickerponent.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);
    }
}

And this is the view (from parent ponent where directive is used):

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

I have difficulties binding to host element 'id' attribute in my select-picker directive. I am using @HostBinding('attr.id'), but it returns undefined. I have checked the actual DOC and it looks like this is the way this simple task should be done.

Here is my ponent:

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

@Component({
    selector: '[select-picker]',
    templateUrl: 'select-picker.ponent.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);
    }
}

And this is the view (from parent ponent where directive is used):

<div select-picker id="page-options" [options]="pageOptions" [elemWidth]="'200px'" (value)="setItemsPerPage($event)"></div>
Share Improve this question asked Oct 19, 2017 at 7:54 markoffdenmarkoffden 1,4681 gold badge15 silver badges35 bronze badges 2
  • is this attr.id a static element? or you generate it dynamiclly? – Paweł Lubczyński Commented Oct 19, 2017 at 8:03
  • I just want to grab static value of the host 'id' attribute for the purpose of later use in jQuery lib init (and not to use constructor (@Attribute()) – markoffden Commented Oct 19, 2017 at 8:06
Add a ment  | 

3 Answers 3

Reset to default 4

Attribute binding for static values can also be done with simple:

@Input() id: string;

Both versions - <div id="some-static-id" ...> and <div [id]="someDynamicId" ...> - will set the value on your ponent when using @Input().

EDIT: However, it is strongly discouraged to use jQuery and lookup by IDs in Angular. I would question if your approach is the best option to acplish what you want. You should probably create a separate question where you explain what you try to acplish and what is the best way to do this with Angular.

You could directly retrieve attribute value of element using getAttribute method on directive DOM. This will only work when you have static element id. If you want to pass id dynamically, use Input bindings.

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

Plunker Demo

If you want to grab a Id value just use @ViewChild not @HostBinding

<div #myDiv></div>


@ViewChild('myDiv') myDiv: ElementRef;

console.log(this.myDiv.nativeElement.id)

and then use methods of ElementRef do get id attribute

发布评论

评论列表(0)

  1. 暂无评论