Angular 5 [对象 HTMLDivElement]

Meh*_*t S 5 html typescript angular angular5

当我单击按钮时,我将“copyRow”元素发送到“copyItem”方法。我将“copyItem”元素与“Typescript”文件中的“item”变量进行均衡。

当我想显示“[object htmldivelement]”时,这个“html 文件中的项目”变量将作为输出。

创建.component.html

<div class="questions">
    <div class="form-group copy-row" #copyRow>
       <label>Question</label>
       <input type="text" class="form-control" placeholder="Question title">
    </div>
    {{ item }}
</div>
<button type="button" class="btn btn-primary" (click)="copyItem(copyRow)">Add</button>
Run Code Online (Sandbox Code Playgroud)

创建组件.ts

  item;

  constructor() { }

  ngOnInit() {
  }

  copyItem(row) {
    this.item = row;
  }
Run Code Online (Sandbox Code Playgroud)

编辑

我的目标是做一个调查项目。当我单击“添加”按钮时,相同的“#copyRow”元素将显示在 {{ item }} 部分中。但是,我得到了类似于第二个链接的输出。

1: http: //prntscr.com/j1ncp1 2: http: //prntscr.com/j1nd19

pla*_*ter 3

我不确定你想用这个实现什么,但这是对你的代码中发生的事情的解释。

#copyRow是对 HTML 元素的引用,在本例中它是一个 div 元素。因此,当您使用函数传递引用时copyItem,您实际上是在传递 HTML 元素。

将这些东西放在一起,该copyItem方法得到以下签名 -

public item: HTMLElement;

public copyItem(row: HTMLElement): void {
    this.item = row;
    //this is how you get inner HTML
    console.log(row.innerHTML);
    //this is to get inner text
    console.log(row.innerText);
}
Run Code Online (Sandbox Code Playgroud)

[object HTMLDivElement]这就是您进入模板进行绑定的原因item(您正在尝试显示一个对象)。

您可以简单地使用{{item.innerHTML}}{{item.innerText}}来显示所选 HTML 元素的内部内容。

如果我遗漏了什么,请告诉我。

编辑-替代方式(模板中的绑定)

如果您不在组件中执行其他操作,则绑定可以像将 HTML 元素引用直接分配给item模板本身的属性一样简单 -

<div class="questions">
    <div class="form-group copy-row" #copyRow>
    <label>Question</label>
    <input type="text" class="form-control" placeholder="Question title">
    </div>
    {{ item?.innerHtml }}
    {{ item?.innerText }}
</div>
<button type="button" class="btn btn-primary" (click)="item = copyRow">Add</button>
Run Code Online (Sandbox Code Playgroud)

编辑2(根据评论中的讨论)

尝试使用此模板在按钮单击时迭代相同的 HTML -

<div class="questions">
<ng-container *ngFor="let item of items">
    <div class="form-group copy-row">
        <label>Question</label>
        <input type="text" class="form-control" placeholder="Question title" />
    </div>
</ng-container>
<button type="button" class="btn btn-primary" (click)="items = items || []; items.push(1);">Add</button>
Run Code Online (Sandbox Code Playgroud)

只需将items数组初始化为 -

public items: Array<number> = [1];
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助 :)