首页 > 解决方案 > 如何在打字稿中访问组件

问题描述

我有一个基本的 Angular 应用程序,如下所示:

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>

如您所见,我输入用户,当我单击“添加更多用户”按钮时,应执行以下方法:

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());
  }
}

克隆组件只包含名字和姓氏的输入,以便添加更多用户。现在,当我单击按钮时,它只是将 [object Object] 附加到“cloneContainer”。可能是什么错误?

标签: javascripthtmlangulartypescript

解决方案


You are looking at this the wrong way, please go through https://angular.io/tutorial to learn the basics of angular. That being said, this is the perfect use case for a child component. The child component is a dumb component in this case, just taking in an object. I created an array of users, passing one user in initially and when clicking button pushing more users into the array. The dumb component only displays these form fields. I attached ngModel to bind the values as well. You will learn all this in the tutorial, but to get you started... create an interface:

export interface User {
  firstName: string;
  lastName: string;
}

Great, now we have a model, as we are using TypeScript, it can now help us in the IDE if we are doing something silly. Next, create an array, push an initial object to it:

users = [{ firstName: '', lastName: ''}] as User[];

Cool... now the function that will be called when we want to add more users:

addUser() {
  this.users.push({ firstName: '', lastName: ''})
}

And over to the child, we'll just call it DumbComponent. We declare @Input() for the child, as we will be feeding the user object to it:

@Input() user: User;

Ok, and the child template will just have two fields, the firstname and lastname, bound with ngModel:

<input [(ngModel)]="user.firstName" placeholder="First Name"/>
<input [(ngModel)]="user.lastName" placeholder="Last Name"/>

Then we in parent iterate the users array and display a child component which is fed the current user in iteration:

<dumb-component *ngFor="let user of users" [user]="user"></dumb-component>

and the button of course:

<button (click)="addUser()">Add user</button>

That's it! Read through the tutorial linked on top, you will learn the basics of angular right there! :)


推荐阅读