Angular [] in view and @Input in component

Discussão em 'Angular' iniciado por user1169587, Março 10, 2025.

  1. user1169587

    user1169587 Guest

    In most angular tutorial, property binding [] is display value from component to view (Property binding moves a value in one direction, from a component's property into a target element property.)

    https://v17.angular.io/guide/property-binding

    But in attached example https://stackblitz.com/edit/angular...e.ts,app/app.component.html,app/app.module.ts

    html

    <div appSampleColorChange [color]="'red'" [backgroundColor]="'blue'">
    Text using directive
    </div>


    ts

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

    @Directive({
    selector: '[appSampleColorChange]',
    })
    export class SampleColorChangeDirective {
    @Input() color: string = '';
    @Input() backgroundColor: string = '';

    constructor(private el: ElementRef) {}

    @HostListener('mouseleave') onMouseLeave() {
    this.el.nativeElement.style.backgroundColor = 'green';
    }

    @HostListener('mouseenter') onMouseEnter() {
    this.el.nativeElement.style.color = this.color;
    this.el.nativeElement.style.backgroundColor = this.backgroundColor;
    }
    }

    1. the ts color property read the value 'red' from html to ts, why the direction is different? due to the use of @Input? My example is mainly come from part of https://www.geeksforgeeks.org/how-to-use-create-custom-directive-in-angular/

    Continue reading...

Compartilhe esta Página