【问题标题】:Footnotes on touch device with Angular带有 Angular 的触摸设备上的脚注
【发布时间】:2017-08-08 11:45:35
【问题描述】:

我希望我的 Angular 应用能够在移动设备上显示带有点击事件的脚注对于使用 nativeElement.innerHTML 注入的文本。我认为我在第一次尝试时没有很好地解释它,所以我会再试一次。我实际上已经阅读了有关模板和数据绑定的内容。问题是当文本被注入时它不起作用 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

有没有办法做到这一点?

谢谢!

【问题讨论】:

    标签: javascript jquery html angular ionic3


    【解决方案1】:

    在 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;
    }
    

    您一定阅读过有关 Template & Data binding 的文档。

    不要在 Angular 之外与 DOM 交互,除非您知道自己在做什么并且确实需要这样做。

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

    【讨论】:

    • 好的,但是页面可能有几十个脚注,我只想显示他们点击的那个。你能在 html 里面放一个按钮,它是用 .innerHTML 注入的吗??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    相关资源
    最近更新 更多