Zum Hauptinhalt springen
Echtzeit-Radar & Feeds
Alle RSS Feeds ➔
👥 Community & Social
••••••••••••••••••••
Intelligence View
⚡ tsecurity.de Intelligence

How to Dynamically Create Components in Angular 6 with ViewChild?

Introduction In Angular applications, especially when dealing with dynamic components, it's common to face challenges related to identifying and managing multiple instances of components. For instance, you might want to dynamically load…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!

Introduction



In Angular applications, especially when dealing with dynamic components, it's common to face challenges related to identifying and managing multiple instances of components. For instance, you might want to dynamically load components within an accordion, leveraging Angular's templating features like <ng-container> and <ng-template>, ensuring that each instance can be referenced correctly using @ViewChild.



In this article, we’ll explore how to achieve dynamic component loading in an Angular 6 application, addressing the specific scenario you described.



Understanding the Problem



You’re trying to create an accordion with dynamic components where every div for dynamic insertion needs a unique reference. When you loop through a list of items, Angular does not automatically bind the ViewChild references that you define with a template variable (#) when using the *ngFor directive, which results in the ViewContainerRef being undefined.



This happens because Angular creates a new context for each iteration of *ngFor which doesn’t allow for direct manipulation of variable scopes, leading to the inability of @ViewChild to recognize your dynamically generated references.



Suggested Solution



To effectively control dynamic components within *ngFor, you can use the ViewChild in combination with the @ViewChildren decorator, which allows for the retrieval of multiple references from the DOM. Here’s how you can implement it:



Step 1: Modify Your Template



Use ng-container to create a structure that allows for component creation dynamically within the loop:



<app-create-feature-modal></app-create-feature-modal>
<app-button description="{{ 'pages[knowledge_base][buttons][accordion_add]' | translate }}" class="btn btn-primary btn-md accordion-button" (callFunction)="add()"></app-button>
<div class="acc">
<ng-container *ngFor="let item of meta; let i = index">
<button class="accordion" (click)="toggle(i)">{{item.name}}</button>
<div class="panel panel-{{i}}">
<div #dynamicContainer></div> <!-- Reference for ViewChild -->
</div>
</ng-container>
</div>


Step 2: Update Your Component Class



Replace your @ViewChild with @ViewChildren to collect references to all dynamic containers:



import { Component, ViewChildren, QueryList, ViewContainerRef, AfterViewInit } from '@angular/core';

@Component({
selector: 'your-selector',
templateUrl: './your-template.component.html',
})
export class YourComponent implements AfterViewInit {
@ViewChildren('dynamicContainer', { read: ViewContainerRef }) dynamicContainers: QueryList<ViewContainerRef>;

ngAfterViewInit() {
this.loadDynamicComponents();
}

loadDynamicComponents() {
this.dynamicContainers.forEach((container, index) => {
// Load your dynamic component here
// e.g., container.clear(); and container.createComponent(YourDynamicComponent);
});
}

toggle(index: number) {
// Add logic to handle accordion toggle
}

add() {
// Add logic to handle the addition of more components
}
}


Explanation





  • Using ng-container: Allows you to utilize structural directives like *ngFor without adding extra elements to the DOM.


  • @ViewChildren: This query will capture all instances specified with the #dynamicContainer reference, thus allowing you to manipulate them easily in your component logic. This ensures no loss of reference when looping through items.



Step 3: Dynamic Component Loading



To load your dynamic component into the specified containers, use the loadDynamicComponents method. Here, you utilize the ViewContainerRef to create instances of your components dynamically:



import { YourDynamicComponent } from './your-dynamic.component';

loadDynamicComponents() {
this.dynamicContainers.forEach((container, index) => {
const componentRef = container.createComponent(YourDynamicComponent);
// You can then set inputs or other properties on componentRef
});
}


Frequently Asked Questions



1. Can I use id instead of ViewChild for dynamic references?



No, using IDs to reference dynamic components created within an *ngFor directive won't yield the results you need due to the way Angular manages scope and view encapsulations.



2. How do I maintain component state when updating?



To retain the state of dynamically loaded components, consider using a service to manage shared state or ensuring inputs are properly set when re-creating instances.



3. Is there an Angular lifecycle hook for dynamic components?



Yes, you can use ngAfterViewInit to execute code after your dynamic components are initialized, or use ngOnInit within your dynamic component for its own initialization logic.



Conclusion



By following this structured approach, you can effectively manage dynamic component creation within an Angular accordion. Remember to utilize @ViewChildren for capturing multiple ViewContainerRef instances, ensuring a robust and maintainable codebase. This method can be applied broadly across components where dynamic features are necessary.

1. Sofort-Triage & Abwehrmaßnahmen

SOC Incident Playbook: Vulnerability Remediation & Verification
Syntax validiert (0 Fehler)
title: Detect Exploitation - How to Dynamically Create Components in Angular 6 with ViewChild?
id: ff2b20e3-e08b-477e-a49f-42724461aed0
status: experimental
description: Automatisch generierte SIEM-Erkennungsregel basierend auf CTI Intelligence
references:
  - https://tsecurity.de/
author: iShareStuff CTI Automated Detection Engine
date: 2026-09-25
logsource:
  category: network_connection
  product: any
detection:
  selection:
      CommandLine|contains:
        - 'exploit'
  condition: selection
falsepositives:
  - Legitime administrative Zugriffe oder Penetrationstests
level: high
tags:
  - attack.initial_access
Syntax validiert (0 Fehler)
rule CTI_Threat_Indicator {
    meta:
        author = "iShareStuff CTI Automated Detection Engine"
        date = "2026-09-25"
        description = "YARA Signature for "
    strings:
        $str = "How to Dynamically Create Comp" ascii wide
    condition:
        any of them
}
Syntax validiert (0 Fehler)
index=security sourcetype IN ("cisco:asa", "pan:traffic", "zeek_conn", "suricata", "WinEventLog:Security")
("How to Dynamically Create Components in ")
| stats count earliest(_time) as first_seen latest(_time) as last_seen by src_ip, dest_ip, dest_host, signature
| eval first_seen=strftime(first_seen, "%Y-%m-%d %H:%M:%S"), last_seen=strftime(last_seen, "%Y-%m-%d %H:%M:%S")
| sort - count
Syntax validiert (0 Fehler)
message: "*How to Dynamically Create Components in *"
Syntax validiert (0 Fehler)
CommonSecurityLog
| where Message has "How to Dynamically Create Components in "
| summarize EventCount = count(), FirstSeen = min(TimeGenerated), LastSeen = max(TimeGenerated) by SourceIP, DestinationIP, DestinationPort, Activity
| extend DetectionRule = "iShareStuff-CTI-Compiled"
| sort by EventCount desc

2. Cyber Threat Intelligence & Forensik

🎯
MITRE ATT&CK Matrix Navigator 14 Taktiken
Reconnaissance
-
Resource Development
-
Initial Access
Execution
Persistence
-
Privilege Escalation
Defense Evasion
Credential Access
-
Discovery
-
Lateral Movement
-
Collection
-
Command and Control
Exfiltration
-
Impact
tsecurity.de Cognitive Threat RAG
Fokus-Vektor:

Kognitive Analyse für identifizierte Bedrohung: Erhöhte Bedrohungslage im Bereich How to Dynamically Create Components in .... Basierend auf 368k Vektor-Korrelationen werden sofortige Isolationsmaßnahmen für betroffene Endpunkte empfohlen.

🛡️ Angriffsfläche & Exposure

Netzwerk/Remote-Zugriff ohne Vorauthentifizierung möglich.

⚡ Empfohlene Sofortmaßnahmen
  • 1. Perimeter-Inspektion: Relevante Portfreigaben und exponierte Endpunkte unverzüglich scannen.
  • 2. Patch-Applikation: Hersteller-Hotfix einspielen oder betroffene Daemons in isolierte DMZ-Segmente überführen.
  • 3. Telemetrie & EDR-Alerts: Prozessaufrufe und Child-Processes auf anomale Shell-Spawns überwachen.
🔗 Semantisch verwandte Zero-Days MariaDB 11.7 VEC
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten How to Dynamically Create Components in Angular 6 with ViewChild?

Thematisch verwandte Begriffe: Dynamically, Create, Components, Angular · 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 ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-87722 | Uncontrolled Resource Consumption (CWE-400 / CWE-1333) in regex search q…
Advisory →
tsecurity.de Icon
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel • Rechts: nächster Artikel • unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel TTP ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...
↗ Original-Quelle