2017-08-08 16 views
0

触摸屏设备上,我想我有角的应用程序能够与nativeElement.innerHTML注入移动设备文本显示与click事件的注脚。我不认为我在第一次尝试中做了很好的解释,所以我会再试一次。我实际上已经阅读过关于模板和数据绑定的内容。问题在于,当文本使用nativeElement.innerHTML注入时,它不起作用,所以我需要其他一些方法来执行此操作。这里有一些代码和一个失败的plunkr。脚注与角

import {Component, NgModule, VERSION, ViewChild, ElementRef} from '@angular/core' 
import {BrowserModule} from '@angular/platform-browser' 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h2>Hello {{name}}</h2> 
     <button (click)="toggleFootNotes()">toggle</button> 

     <p>Text in template: 
      And when 
      <sup>a 
       <span *ngIf=this.showFootnotes> testing 1 2 3 </span> 
      </sup> 
      he came ... 
     </p> 

     <div #textwithfootnote></div> 
    </div> 
    `, 
}) 
export class App { 
    @ViewChild('textwithfootnote') textwithfootnote: ElementRef; 
    name:string; 
    public showFootnotes: boolean = false; 
    constructor() { 
    this.name = `Angular! v${VERSION.full}` 
    } 

    public toggleFootNotes() { 
     this.showFootnotes = !this.showFootnotes; 
    } 

    ngAfterViewInit() { 
    this.textwithfootnote.nativeElement.innerHTML = " \ 
    \n<p>Text injected: \ 
    \n And when \ 
    \n  <sup>a \ 
    \n   <span *ngIf=this.showFootnotes> testing 1 2 3 </span> \ 
    \n  </sup> \ 
    \n  he came ... \ 
    \n </p>"; 
    } 

} 

@NgModule({ 
    imports: [ BrowserModule ], 
    declarations: [ App ], 
    bootstrap: [ App ] 
}) 
export class AppModule {} 

http://plnkr.co/edit/wY2vRt4dcMHq12SlJSmv

有没有办法做到这一点?

谢谢!

回答

0

在angular中,您可以使用模板中的() -syntax或通过HostBinding装饰器绑定事件侦听器。并绑定一些HTML,通过innerHTML属性指令绑定它。但你也可以使用简单的ng-template来显示和隐藏脚注。作为指令前缀的*只是语法糖,它会自动将元素包装在ng-template中。

内,您的组件的模板:

<button (click)="toggleFootNotes()">toggle</button> 
... 
<p *ngIf="showFootNotes"> 
    My footnotes. 
</p> 

和您的组件中:

public showFootNotes: boolean = false; 

... 

public toggleFootNotes() { 
    this.showFootnotes = !this.showFootNotes; 
} 

您要高度重视definitly了解Template & Data binding的文档。

不要具有角外DOM的互动,除非你知道自己在做什么,真正需要去做。

所以你应该摆脱jQuery,你不会需要它。

+0

好的,但页面可能有几十个脚注,我只想显示他们点击的那个。你可以把一个按钮注入.innerHTML的HTML内? – John