【问题标题】:Angular 2 hide parent element on click on close buttonAngular 2在单击关闭按钮时隐藏父元素
【发布时间】:2017-01-31 18:57:27
【问题描述】:

我是 Angular2 的新手,我想在单击关闭图标后隐藏父元素。以下是我的代码:

@Component({
    selector: 'add-search',
    template: `
      <input type='text' #newHero
        (keyup.enter)="addHero(newHero.value)"
        (blur)="addHero(newHero.value); newHero.value='' ">
      <button (click)=addHero(newHero.value)>Add</button>
    <div>
    <div [hidden]="hideElement" style="margin-right:2px" *ngFor="let hero of heroes" class="label label-primary">{{hero}}<span (click)="toggleElement()" style='cursor:pointer; display:inline-block; padding:1px 2px;'><i class="fa fa-times" aria-hidden="true" style="font-size:10px;"></i></span>
</div>
</div>
   `
})
export class AddSearchComponent {
    heroes = Array<string>();
    addHero(newHero: string) {
        if (newHero) {
            this.heroes.push(newHero);
        }
    }
    private hideElement: boolean = false;
    toggleElement() {
        if (this.hideElement) {
            this.hideElement = false;
        else
            this.hideElement = true;
    }
}
}

隐藏在代码中不起作用。我们可以用简单的方式来做吗?或者最好的方法是什么?

【问题讨论】:

    标签: angular typescript1.8


    【解决方案1】:
    <div [hidden]="hero.hideElement" style="margin-right:2px" 
         *ngFor="let hero of heroes" 
          class="label label-primary">{{hero}}
    
           <span (click)="hero.hideElement=!hero.hideElement"
                  style='cursor:pointer; display:inline-block; padding:1px 2px;'>
                  <i class="fa fa-times" aria-hidden="true" style="font-size:10px;"></i>
           </span>
    </div>
    
    // toggle is not possible.
    

    <span  *ngFor="let hero of heroes"  
            (click)="hero.hideElement=!hero.hideElement"
            style='cursor:pointer; display:inline-block; padding:1px 2px;'>   
            <i class="fa fa-times" aria-hidden="true" style="font-size:10px;"></i>
    
        <div [hidden]="hero.hideElement" style="margin-right:2px"          
              class="label label-primary">
              {{hero}}    
        </div>
    </span>
    
    // toggle is possible.
    

    更新

    您不清楚您使用的是 Array 还是 Array of objects。 所以我给了你对象数组

    的解决方案

    使用字符串数组,无法通过 *ngFor 循环隐藏元素。你所能做的就是拼接

    在此处检查两种方式。

    http://plnkr.co/edit/fc7x4nCh6vFIbIL2IX4I?p=preview

    【讨论】:

    • 谢谢@micronyks。实际上,如果需要,我想在页面上添加文本后删除它。我只是尝试使用切换来实现。对我来说不幸的是,它不像我上面所说的那样工作。
    • 所以你可以遵循第一个建议。它会起作用的。您不需要 ts 文件中的单击事件功能。如图所示,您可以从 hTML 本身处理它。
    • 点击两个建议中的关闭图标后,我无法关闭。
    • 请仔细检查我的两个解决方案。如果您使用的是 HERO 模型,则将 hideElement:boolean=false 属性添加到该模型。否则建议的解决方案必须有效。
    • 非常感谢您的所有努力。我可能做错了什么。请查看实时代码link
    猜你喜欢
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多