Home > OS >  How to access component in typescript
How to access component in typescript

Time:11-16

I have a basic Angular Application looking like this:

app.component.html:

<head>
  <title> My Home Page </title>
</head>
<body>

<h1>Test Umgebung</h1>

<div>
  <label>Firstname</label>
  <input placeholder="Firstname"/>
</div>
<div>
  <label>Lastname</label>
  <input placeholder="Lastname"/>
</div>

<div id="cloneContainer">

</div>

<button (click)="cloneUpper()">  Add more Users</button>

</body>


</html>

As you can see, I type in Users and when I click on the "Add more Users" button, the following method should be executed:

app.component.ts:
import { Component } from '@angular/core';
import { CloneComponentComponent } from './clone-component/clone-component.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'UserManager';

  cloneUpper(){
    console.log("Cloned!");
    var cln = new CloneComponentComponent();    
    var container = document.getElementById('cloneContainer');
    container?.append(cln.toString());
  }
}

The clone component just contains a input for firstname and lastname in order to add more users. Now, when I click the button, it just appends [object Object] to the "cloneContainer". What could be the mistake?

CodePudding user response:

First suggest relationships, such as parent-child relationships, ways to get child components via viewChild, or public parameters via service

CodePudding user response:

In Angular you don't need to get from DOM via getElementById anything. Just add conditional rendering:

<div id="cloneContainer">
  <!-- CloneComponentComponent selector -->
  <clone-component *ngIf="showClone"></clone-component> 
</div>

Now your clone is visible only when showClone = true, so let's add this varable into your AppComponent and change cloneUpper method:

export class AppComponent {
  title = 'UserManager';
  showClone = false;

  cloneUpper(){
    this.showClone = true;
  }
}

In case you need to handle array of clild components (push new ones) you can do the same trick with array:

<div id="cloneContainer">
  <!-- CloneComponentComponent selector -->
  <clone-component *ngFor="let clone of clones"></clone-component> 
</div>
export class AppComponent {
  title = 'UserManager';
  clones = [];

  cloneUpper(){
    this.clones.push(true); // whatever you want
  }
}
  • Related