繁体   English   中英

加载和卸载angular6组件

[英]Load and unload angular6 component

我试图在单击图像时创建图像模态。 我已经设置好了,以便在单击图像时加载子组件。 问题在于,它只能被单击一次,并且在关闭后将其设置为display: none

可以通过单击子组件中的关闭按钮来关闭它。 但是我只能通过display: none做到这一点display: none CSS中display: none ,使该组件不可见,但仍处于活动状态。

我最终想要的是一种在按下关闭按钮时卸载该子组件的方法。 或设置opacity: 1再次单击父级中的图像时。

HTML父级:

<app-image-modal
    *ngIf="clicked"
    [slice] = "slice"
    [clicked] = "clicked">
</app-image-modal>

<img src"img.png" (click)="imageClicked()"/>

TS家长:

export class ImageComponent {
public clicked = false;

public imageClicked() {
    this.clicked = true;
}
}

HTML子级:

<section [ngClass]="{'hide': hide}">
  <div [ngClass]="{'active': show}">

    <img src"img.png" />

    <div class="close" (click)="hideModal()">
        <button>X</button>
    </div>

  </div>                                                              
</section>

TS孩子:

export class ImageModalComponent implements OnInit {
public show = false;
public hide = false;

@Input() clicked: boolean;

public ngOnInit() {
    this.show = true;
}

public hideModal() {
    this.show = false;
    this.hide = true;
}
}

我认为您的组件沟通很落后

结束信息应从孩子到父母。 要实现此目的:您可以在子组件中有一个EventEmitter,然后从父组件中监听它。

然后,如果要卸载子组件,则可以在父模板的子组件中使用带*ngIf的布尔值。

显示或不显示模式的事实应在父级别处理(例如:不需要布尔值在子级中显示和隐藏,顺便说一句,您可以只使用一个布尔值而不是两个布尔值来处理)。

为什么在父母一级? 因为您要卸载组件,而不仅仅是隐藏它。

代码示例:

**在子组件**中:

export class ImageModalComponent implements OnInit {
    @Output() close = new EventEmitter();

    public hideModal() {
        this.close.emit(); // here we tell the parent that the "close" button has been clicked.
    }
}

在子HTML中,删除所有依赖于“ show”和“ hide”的内容(假定显示了该组件):

<section>
  <div class="active">
  ...

**在父模板中:**

export class ImageComponent {

    public clicked = false;

    public imageClicked() {
        this.clicked = true;
    }

    public childCloseEventHandler(): void {
        this.clicked = false; // this will trigger the unload of the child, since you have `*ngIf="clicked"` for the child component
    }
}

HTML父级:

<app-image-modal
    *ngIf="clicked"
    [slice]="slice"
    (close)="childCloseEventHandler()">   <!-- I changed this line -->
</app-image-modal>

<img src"img.png" (click)="imageClicked()"/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM