【问题标题】:Show text when image is clicked单击图像时显示文本
【发布时间】:2017-06-08 18:04:37
【问题描述】:

当我点击我的图片时,我试图在我的标题下方显示一些文本。 OnClick,它应该显示下面的文本段落。但是,我对我当前的实现有什么问题感到困惑。

到目前为止,这是我的 html 代码:

我有一个问题,例如,它旁边是一个加号。当我单击加号时,showAnswer 从 false 变为 true,然后它应该 showAnswer 但页面加载时已显示所有内容。我该如何解决?

<h1 class="question"> Foo?
    <img (click)="showAnswer = !showAnswer" style="float:right;" src="images/ic-add.png"
     class="ic_add"/></h1>
<p *ngIf="showAnswer" class="answer" > Bar</p>
<hr/>
<h1 class="question" >ABC
    <img (click)="showAnswer = !showAnswer" style="float:right;" src="images/ic-add.png" class="ic_add"/>
</h1>
<p  *ngIf="showAnswer" class="answer">123</p>
<hr/>

ts:

export class QuestionsComponent {   

    public showAnswer = false; 

    constructor(){                
    }

}

【问题讨论】:

标签: html angular typescript


【解决方案1】:

你的代码没有问题。

我已经发了example

你可以检查一下。

更新

支持ngFor多问。

//our root app component
import {Component, View, CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/angular2'
import {Question} from './question'

@Component({
  selector: 'my-app',
  bindings: []
})
@View({
  template: `
      <question *ng-for="#el of questionArray; #idx = index"></question>
  `,
  directives: [CORE_DIRECTIVES, FORM_DIRECTIVES, Question]
})
export class App {
  questionArray: Object[] = [1,2];
}




import {Component, View, CORE_DIRECTIVES} from 'angular2/angular2'

@Component({
  selector: 'question',
  bindings: []
})
@View({
  template: `
    <h1 class="question"> Foo?
        <img (click)="clicked()" style="float:right;" src="images/ic-add.png"
         class="ic_add"/></h1>
    <p *ng-if="showAnswer" class="answer"> Bar</p>
    <hr/>
  `,
  directives: [CORE_DIRECTIVES]
})
export class Question {

  showAnswer: bool = false;

  clicked() {
    this.showAnswer = !this.showAnswer;
  }
}

【讨论】:

  • 哦,我注意到一件事...我只希望单击的图标显示其下方的元素/文本,而不是页面上的所有隐藏元素。看起来像这里,如果我点击图片,它会显示所有隐藏的文字。
  • @Euridice01 我已经更新了这个例子。你可以检查一下。
  • 谢谢,只是好奇。为什么你使用两个组件而不是一个?
  • oop 如果你想让一个组件管理两个语句,你必须让Question有两个字段showAnswer1showAnswer2。我认为这不是你想要的。
  • 是的,这不是我想要的。另外,如果我有 X 数量的问题和答案,这种方法会起作用吗? Angular 2 中不再存在视图符号。我相信它已被弃用。
猜你喜欢
  • 2014-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多