🕵️ SicherheitslückenHak5: Hackers Just Poisoned the Rust Supply Chain | Threat Wire(01.09.2026 um 14:00 Uhr)
🕵️ SicherheitslückenHak5: Hackers Found a Way Into Humanoid Robots | Threat Wire(04.09.2026 um 15:04 Uhr)
🔧 AI Nachrichten Bits und so #1021 (Passwort für Laufwerk)(31.08.2026 um 22:15 Uhr)
🔧 AI Nachrichten Bits und so #1022 (Wie Weißbier)(06.09.2026 um 20:39 Uhr)
🍏 iOS / Mac OSHue-App 6.0 ist da: das sind die Neuerungen(07.09.2026 um 17:21 Uhr)
🕵️ SicherheitslückenHak5: Hackers Just Poisoned the Rust Supply Chain | Threat Wire(01.09.2026 um 14:00 Uhr)
🕵️ SicherheitslückenHak5: Hackers Found a Way Into Humanoid Robots | Threat Wire(04.09.2026 um 15:04 Uhr)
🔧 AI Nachrichten Bits und so #1021 (Passwort für Laufwerk)(31.08.2026 um 22:15 Uhr)
🔧 AI Nachrichten Bits und so #1022 (Wie Weißbier)(06.09.2026 um 20:39 Uhr)
🍏 iOS / Mac OSHue-App 6.0 ist da: das sind die Neuerungen(07.09.2026 um 17:21 Uhr)

🔧 Programmierung 🕛 kürzlich 12 Min Lesezeit
0

Mastering Angular Structural Directives - It’s all about the context

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht

In the .

  • By default, we convert from USD to EUR

  • We call an API to return the current rate between the currencies

  • Once we get the value we render our template and expose:

    1. the from currency code

    2. the to currency code

    3. the rate

    4. a reverse function, which can be called to switch the from and to variables. Reversing the current rate


  • Using it in a component should be as easy as this:




    CODE
    @Component({
    selector: 'my-app',
    template: `
    <label>From <input [(ngModel)]="fromInput"> </label>
    <label>To <input [(ngModel)]="toInput"> </label>

    <ng-template exchangeRate [from]="fromInput" [to]="toInput" let-from="from" let-to="to" let-rate="rate" let-refresh="refresh">
    <p>Converting from {{from}} to {{to}} the exchange rate is: {{rate}}</p>
    <button (click)="refresh()">Reverse</button>
    </ng-template>
    `
    ,
    })
    export class AppComponent {
    public fromInput = 'USD';
    public toInput = 'EUR';
    }






    Let's look at the overall structure of how our directive might implement this functionality:




    CODE
    @Directive({
    selector: '[exchangeRate]',
    })
    export class ExchangeRateDirective implements OnInit, OnChanges {
    // from input which defaults to USD if none is provided
    @Input('from')
    public from = 'USD';
    // to input which defaults to EUR if none is provided
    @Input('to')
    public to = 'EUR';

    // TemplateRef and ViewContainerRef to render to DOM
    private template = inject(TemplateRef);
    private vcr = inject(ViewContainerRef);
    // HttpClient to query API
    private http = inject(HttpClient);

    // initally we render our template with the default values
    public ngOnInit(): void {
    this.getExchangeRateFromApiCreateContextRenderTemplate();
    }

    // whenever an input value changes we query our
    // api for the new rate and re-render the template
    // given the new input is a 3 letter currency code
    public ngOnChanges(changes: SimpleChanges): void {
    // get the new from value or keep old
    const newFrom = changes.from ? changes.from.currentValue : this.from;
    // get the new to value or keep old
    const newTo = changes.to ? changes.to.currentValue : this.to;
    // over simplified check if inputs are currency code
    if (newFrom.length !== 3 || newTo.length !== 3) {
    // stop processing changes as definitely not a valid currency code
    return;
    }
    // get new rate and render template to DOM
    this.getExchangeRateFromApiCreateContextRenderTemplate();
    }

    private getExchangeRateFromApiCreateContextRenderTemplate(): void {
    ...
    }

    public reverseRate() {
    // this is for demonstration purposes only
    // since from and to are inputs reassigning those inputs
    // might be confusing to the consumer of the directive
    const oldFrom = this.from;
    this.from = this.to;
    this.to = oldFrom;
    this.getExchangeRateFromApiCreateContextRenderTemplate();
    }
    }






    First, we take in our from and to inputs with the defaults from the requirements. Then, we inject our dependencies which we need to render our template to the DOM and make API calls to get the newest exchange rate.




    CODE
      // from input which defaults to USD if none is provided
    @Input('from')
    public from = 'USD';
    // to input which defaults to EUR if none is provided
    @Input('to')
    public to = 'EUR';

    // TemplateRef and ViewContainerRef to render to DOM
    private template = inject(TemplateRef);
    private vcr = inject(ViewContainerRef);
    // HttpClient to query API
    private http = inject(HttpClient);






    On initialization, we get the exchange rate from the API, create the context and render the template.




    CODE
      // initally we render our template with the default values
    public ngOnInit(): void {
    this.getExchangeRateFromApiCreateContextRenderTemplate();
    }






    On every subsequent change, we determine if the inputs changed and if they are a currency code. If they did not, we do nothing. If they did, we again get the exchange rate from the API, create the context and render the template.




    CODE
      // whenever an input value changes we query our
    // api for the new rate and re-render the template
    // given the new input is a 3 letter currency code
    public ngOnChanges(changes: SimpleChanges): void {
    // get the new from value or keep old
    const newFrom = changes.from ? changes.from.currentValue : this.from;
    // get the new to value or keep old
    const newTo = changes.to ? changes.to.currentValue : this.to;
    // over simplified check if inputs are currency code
    if (newFrom.length !== 3 || newTo.length !== 3) {
    // stop processing changes as definitely not a valid currency code
    return;
    }
    // get new rate and render template to DOM
    this.getExchangeRateFromApiCreateContextRenderTemplate();
    }






    Finally, we define a reverse function that reverses the from and to variable, then gets the reversed rate from the API, creates the context, and renders the template.




    CODE
      public reverseRate() {
    // this is for demonstration purposes only
    // since from and to are inputs reassigning those inputs
    // might be confusing to the consumer of the directive
    const oldFrom = this.from;
    this.from = this.to;
    this.to = oldFrom;
    this.getExchangeRateFromApiCreateContextRenderTemplate();
    }






    Let's take a closer look at the getExchangeRateFromApiCreateContextRenderTemplate method and see how it ties everything together.




    CODE
      private getExchangeRateFromApiCreateContextRenderTemplate(): void {
    // 1. we get the new rate based on the from and to currencies and re-render our template
    this.http
    .get(`https://open.er-api.com/v6/latest/${this.from}`)
    .pipe(
    // 2. we only care about the immediate response
    take(1),
    // 3. we extract the rate for the currency
    // we convert to
    map((response: ExchangeRateResponse) => {
    return response?.rates?.[this.to] ?? -1;
    })
    )
    .subscribe((rate) => {
    // 4. once the rate arrives, we build the
    // context which will be exposed to our template.
    const exchangeRateContext = {
    // 4.1 current value of our from property
    from: this.from,
    // 4.2 current value of our to property
    to: this.to,
    // 4.3 rate returned by api
    rate,
    // 4.4 function reference to refresh
    reverseFn: () => this.reverseRate(),
    };
    this.vcr.clear();
    // 5. we render the template with the new context
    this.vcr.createEmbeddedView(this.template, exchangeRateContext);
    });
    }






    1. The method uses the HttpClient's get method to request a new rate from the API for our from currency code and
      returns an observable of the response.

    2. We ensure we only react to the first value emitted using the take(1) RxJs operator.

    3. With the map operator, the API response inside of the observable is mapped to the rate for our to currency code. If we cannot find the code, we return a symbolic value of -1. This indicates to users of our directive that something is off so they can display an appropriate message. Of course, this is oversimplified, but I hope you get the idea.

    4. We subscribe to our observable and obtain the rate.
      Once the rate is received, we build our context with the following keys:


      1. from: the current currency code of our directives from property.


      2. to: the current currency code of our directives to property


      3. rate: the exchange rate returned from the API


      4. reverse: a reference to our directives reverseRate function bound to the current execution context with an arrow function.


    5. We render our template to the DOM and pass the new context.

    Now, we can use our directive in the AppComponent as described above:




    CODE
    @Component({
    selector: 'my-app',
    template: `
    <label>From <input [(ngModel)]="fromInput"> </label>
    <label>To <input [(ngModel)]="toInput"> </label>

    <ng-template exchangeRate [from]="fromInput" [to]="toInput" let-from="from" let-to="to" let-rate="rate" let-refresh="refresh">
    <p>Converting from {{from}} to {{to}} the exchange rate is: {{rate}}</p>
    <button (click)="refresh()">Reverse</button>
    </ng-template>
    `
    ,
    })
    export class AppComponent {
    public fromInput = 'USD';
    public toInput = 'EUR';
    }






    And see our code in action:








    One step at a time



    There are a lot of ways to improve our directive such as improving performance by avoiding re-renders using observables for our exposed variables and strict type checking for our context in the ng-template.



    However, these are topics for another post. If you are interested in how to strictly type your context exposed to templates Thomas Laforge wrote this great article covering everything you need to know. I highly recommend you read it!



    Let's be proud of ourselves today. We took another step to master structural directives in Angular by understanding the key concept of the context. Let's take some time to digest all this new information and get ready to learn everything about the structural directive micro syntax. The magic that brings us back our asterisk.

    Vollständiger Original-Bericht
    Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
    ↗ Original-Artikel auf dev.to lesen
    Wie bewertest du diesen Beitrag?
    1 Klick Feedback
    Teilen mit Netzwerk & Team:

    Community-Analysen & Experten-Meinungen 0

    Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
    Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
    Community Pulse: Relevanz-Einschätzung
    1 Klick Experten-Votum
    🔴 Akute Relevanz 0%
    🟡 In Evaluierung 0%
    🟢 Keine Auswirkung 0%
    Spannende Innovation 0%
    Verwandte Story-Cluster & Quellen (Vektor-KI)
    Port 8095 Engine
    1 Quelle
    Hackers Just Poisoned the Rust Supply Chain | Threat Wire
    1 Quelle
    Hackers Found a Way Into Humanoid Robots | Threat Wire
    1 Quelle
    Bits und so #1021 (Passwort für Laufwerk)
    Ähnliche Beiträge
    🔍 Verwandte News

    Auch interessante Nachrichten Mastering Angular Structural Directives - It’s all about the context

    Thematisch verwandte Begriffe: Mastering, Angular, Structural, Directives · 6 Treffer

    Laden...

    Videos werden geladen ...

    Laden...

    Beiträge werden geladen ...

    Laden...

    Videos werden geladen ...

    Laden...

    Beiträge werden geladen ...

    Laden...

    Videos werden geladen ...

    Laden...

    Beiträge werden geladen ...

    Laden...

    Videos werden geladen ...

    Laden...

    Beiträge werden geladen ...

    Laden...

    Videos werden geladen ...