【问题标题】:Load and unload angular6 component加载和卸载angular6组件
【发布时间】:2019-03-09 13:59:35
【问题描述】:

我正在尝试在单击图像时创建图像模式。我已经设置了它,以便在单击图像时加载子组件。问题是它只能点击一次,关闭后设置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;
}
}

【问题讨论】:

    标签: angular typescript frontend angular6 angular-components


    【解决方案1】:

    我认为您的组件通信落后

    关闭的信息应该从孩子到父母。要实现这一点:您可以在子组件中拥有一个 EventEmitter,并从父组件中监听它。

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

    模态显示或不显示的事实应该在父级处理(例如:不需要在子级中显示和隐藏布尔值,顺便说一下,你可以只用 one em> 布尔值而不是两个)。

    为什么在父级?因为你想卸载组件,而不仅仅是隐藏它。

    代码示例:

    ** 在子组件中**:

    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 中,移除依赖于“显示”和“隐藏”的所有内容(假设组件已显示):

    <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()"/>
    

    【讨论】:

      猜你喜欢
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 2013-07-10
      相关资源
      最近更新 更多