加载和卸载angular6组件

时间:2018-10-04 08:27:58

标签: angular typescript frontend angular6 angular-components

我试图在单击图像时创建图像模态。我已经设置好了,以便在单击图像时加载子组件。问题在于它只能被单击一次,并且在它关闭后将其设置为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;
}
}

1 个答案:

答案 0 :(得分:0)

我认为您的组件通信往后

关闭信息应从子级到父级。要实现此目的:您可以在子组件中有一个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()"/>