How to get element’s width/height within directives and component?

You can use ElementRef as shown below, DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser’s console. import { Directive, Input, Output, ElementRef, Renderer } from ‘@angular/core’; @Directive({ selector:”[move]”, host:{ ‘(click)’:”show()” } }) export class GetEleDirective{ constructor(private el:ElementRef) { } show(){ console.log(this.el.nativeElement); console.log(‘height—‘ + this.el.nativeElement.offsetHeight); //<<<===here console.log(‘width—‘ + this.el.nativeElement.offsetWidth); //<<<===here } } Same way you can use it within … Read more

Get Value From Select Option in Angular 4

As a general (see Stackblitz here: https://stackblitz.com/edit/angular-gh2rjx): HTML <select [(ngModel)]=”selectedOption”> <option *ngFor=”let o of options”> {{o.name}} </option> </select> <button (click)=”print()”>Click me</button> <p>Selected option: {{ selectedOption }}</p> <p>Button output: {{ printedOption }}</p> Typescript export class AppComponent { selectedOption: string; printedOption: string; options = [ { name: “option1”, value: 1 }, { name: “option2”, value: 2 } … Read more

Angular 1.5 component vs. old directive – where is a link function?

EDIT 2/2/16: The 1.5 documentation now covers components: https://docs.angularjs.org/guide/component Some thoughts based on some reading (links below): Components aren’t replacements for directives. A component is a special type of directive that organizes a controller with a template. Components do not have a link function and controllers still are not where you’d handle DOM manipulation. If … Read more

Detect when input value changed in directive

You need to make an input property of input and then use the ngOnChanges hook to tell when the input property changes. @Directive({ selector: ‘[number]’ }) export class NumberDirective implements OnChanges { @Input() public number: any; @Input() public input: any; ngOnChanges(changes: SimpleChanges){ if(changes.input){ console.log(‘input changed’); } } } Plunkr Stackblitz

Make directive @Input required

Official solution As answered by Ryan Miglavs – smart usage of Angular’s selectors solves the issue. /** Note: requires the [a] attribute to be passed */ @Component({ selector: ‘my-dir[a]’, // <– use attribute selector along with tag to ensure both tag name and attribute are used to “select” element by Angular in DOM }); export … Read more