31 Mayıs 2016 Salı

Structural Direktif'ler neler?

Hali hazırdaki structural direktifler

  • ngIf
  • ngFor
  • ngSwitch

ama duruma göre bok ta çıkhabilir yani güvenemiyom :)) Şaka şaka güzel bir örnekle kendi custom structural diretive'imizi de yazabiliriz.

custom-structural-directive.directive.ts


import { Directive, TemplateRef, ViewContainerRef, ElementRef } from '@angular/core';

@Directive({
    selector: '[customStructuralDirective]',
    inputs: ['customStructuralDirective']

})
export class CustomStructuralDirective {
    constructor(private _templateRef: TemplateRef<Object>,
                private _viewContainerRef: ViewContainerRef) { }

    set customStructuralDirective(condition:boolean) {
        if (condition)
            this._viewContainerRef.createEmbeddedView(this._templateRef);
        else
            this._viewContainerRef.clear();
    }
}


app.component.ts


<div *customStructuralDirective="true">
    Deneme
</div>





Burda dikkat edilmesi gereken noktalardan biri direktif kullanılırken
önüne konulan * işareti. Dökümantasyonda bu * işareti dilin syntactic sugar yani kolaylık
sağlayan şekerlerinden biri olarak nitelendiriliyor. * işareti konulduğunda ilgili dom element'inin
içi tamamen alınıp normalde tanımlanan template tag'i içine yerleştiriliyor. Böylece constructor'da
gelen bu template referansı üzerinden bu element içinde dom manüplasyonu
gerçekleştirebiliyorsunuz.

Hiç yorum yok:

Yorum Gönder