【发布时间】:2026-02-08 05:35:01
【问题描述】:
在搜索了大约两个小时的解决方案后,我决定询问一些专业人士,他们怀疑解决方案可能非常简单。
这是一个 Angular7 项目。 我想在我的目标组件中有一个带有“+”按钮的“目标”。当您单击该按钮时,我希望将另一个目标添加到页面中。所以我想点击目标组件的一个按钮来创建一个新目标,这对我来说有点像递归。
goals.component.html:
<input type="text" value="Ich brauche einen Laptop für maximal 1000 Euro.">
<br/>
<br/>
<app-goal id="{{lastGivenId+1}}"></app-goal>
goals.component.ts:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-goals',
templateUrl: './goals.component.html',
styleUrls: ['./goals.component.scss']
})
export class GoalsComponent implements OnInit {
lastGivenId: number = 0;
constructor() { }
ngOnInit() {
}
}
goal.component.ts 和goal.component.html:
//Typescript code
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-goal',
templateUrl: './goal.component.html',
styleUrls: ['./goal.component.scss']
})
export class GoalComponent implements OnInit {
@Input() id : number;
constructor() { }
ngOnInit() {
}
onAddLowerGoal(currentGoalID:number){
// var goalElement = document.registerElement('app-goal');
// document.body.appendChild(new goalElement());
let newGoal = document.createElement("app-goal");
newGoal.setAttribute("id", "999");
let currentGoal = document.getElementById(currentGoalID.toString());
document.body.insertBefore(newGoal, currentGoal);
}
}
<html>
<div id="{{id}}" class="goal">goal{{id}}</div>
<button id="AddLowerGoal1" (click)="onAddLowerGoal(999)">+</button>
</html>
这样,它创建了一个 app-goal 元素,但是 app-goal 元素中的 div 和 button 元素丢失了。 如何解决这个问题?欢迎任何帮助。提前致谢。
【问题讨论】:
标签: html angular typescript components