Angular – Directive – How to fix: Can’t bind to since it isn’t a known property of

Angular

Angular directives are classes that can add new behavior to the elements in the template or modify existing behavior.

How to reproduce it

directive.ts

import { Directive, Input } from '@angular/core';

@Directive({
  selector: '[directiveDemo]'
})
export class DemoDirective {

  constructor() { }

  ngOnInit() {
    console.log(this.directiveDemo)
  }

}

component.html


<div [directiveDemo]="'Directive value'">Directive 1</div>

Solution #1

Add @Input decorator.

directive.ts

import { Directive, Input } from '@angular/core';

@Directive({
  selector: '[directiveDemo]'
})
export class DemoDirective {

  @Input() directiveDemo = "";

  constructor() { }

  ngOnInit() {
    console.log(this.directiveDemo)
  }

}

Solution #2

Add @Input decorator and remove brackets [] from the template.

directive.ts

import { Directive, Input } from '@angular/core';

@Directive({
  selector: '[directiveDemo]'
})
export class DemoDirective {

  @Input() directiveDemo = "";

  constructor() { }

  ngOnInit() {
    console.log(this.directiveDemo)
  }

}

component.html

<div directiveDemo="Directive value">Directive 1</div>
https://www.mldgroup.com

Vyštudovaný top manažér pôsobiaci najmä ako manažér, marketér, softvérový inžinier, konzultant, bloger, YouTuber a zatiaľ neúspešný hudobník a producent. V rámci praxe pôsobil v rôznych odvetviach na rôznych pozíciách v malých aj veľkých firmách, vrátane spoluprác a partnerstiev s významnými firmami či poradenskými spoločnosťami.

Pridaj komentár

Vaša e-mailová adresa nebude zverejnená. Vyžadované polia sú označené *