Angular 8에서 이미 파괴 된 동적 구성 요소를 어떻게 표시 할 수 있습니까?

Jesús Soto Media

저는 앵귤러를 처음 접했습니다. 다음과 같이 작동하는 채팅 응용 프로그램을 만들고 있습니다.

사용자 목록이 있으며 각 사용자를 클릭 할 때 해당 사용자의 메시지가있는 상자를 표시해야 각 상자가 닫힐 수 있습니다. 다 괜찮아요.

내 문제는 각 상자를 닫을 때 해당 사용자를 클릭하면 다시 표시되지 않는다는 것입니다. 클릭 한 사용자의 ID가 배열에 저장되어 있고 해당 ID가 배열에있는 경우 표시되지 않는 것으로 확인 되었기 때문일 수 있습니다. 문제는 내가이 작업을 수행하여 상자가 이미 표시되고 다른 방법을 모르겠습니다.

app.component.ts

import { Component,ViewChild,ViewContainerRef,ComponentFactoryResolver,ComponentRef,OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { tap } from 'rxjs/operators';
import { ConversacionComponent} from "./components/conversacion/conversacion.component";
import {ChatService} from "./services/chat.service";
import {Mensaje} from "./models/mensaje";

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers:[ChatService]
})
export class AppComponent implements OnDestroy {

    /*Esto se usa para poder crear el componente de las ventanas de chat dinamicamente y que cada uno pueda eliminarse*/
    @ViewChild('componentsContainer', { read: ViewContainerRef, static: false }) container: ViewContainerRef;
    private subs: Subscription[] = [];
    /****************/
    public id_usuario_destino:number;
    public personas:Array<any>;
    public id_persona:number;
    public mensajes:Mensaje[];
    public alreadyDone : number[];
    ngOnDestroy() {
        // unsubscribe from all on destroy
        this.subs.forEach(sub => sub.unsubscribe());

    }

    onClickAdd = (elemento) => {
        if(this.alreadyDone.findIndex(x => x === elemento.id) === -1)
        {
            this.alreadyDone.push(elemento.id);
            this.id_usuario_destino=elemento.id;
            this.id_persona=this.id_usuario_destino;
            this._chatService.getMessages(1,this.id_usuario_destino).subscribe(
                response=>{
                    if(response.mensajes){
                        this.mensajes=response.mensajes;
                        /*Este código es para crear las ventanas de chat dinamicas y que cada una pueda cerrarse*/
                        const factory = this.componentFactoryResolver.resolveComponentFactory(ConversacionComponent);
                        const component = this.container.createComponent(factory);
                        component.instance.destino=this.id_usuario_destino;
                        component.instance.numberCreated = this.container.length;
                        component.instance.men = this.mensajes;
                        // subscribe to component event to know when to delete
                        const selfDeleteSub = component.instance.deleteSelf
                            .pipe(tap(() => component.destroy()))
                            .subscribe();
                        // add subscription to array for clean up
                        this.subs.push(selfDeleteSub);
                        /*************************************************************************************/
                    }


                },
                error=>{
                    console.log(error);
                }
            );
        }



    }


    constructor( private componentFactoryResolver: ComponentFactoryResolver,private  _chatService:ChatService) {
        this.alreadyDone=[];
        this.personas=[
            {id:"2",
                nombre:"sergio"
            },
            {id:"3",
                nombre:"jhoyner"
            },
            {id:"4",
                nombre:"gerardo"
            },
            {id:"5",
                nombre:"fabrizio"
            }
        ]
    }



}

app.component.html

<div class="sidenav">
  <ul *ngFor="let persona of personas">
    <li><a id="{{persona.id}}"(click)="onClickAdd($event.target)">{{persona.nombre}}</a></li>
  </ul>

</div>

<ng-template #componentsContainer></ng-template>

dialog.component.html

<button (click)="deleteSelf.emit()" style="background-color: blue; color: white">close window</button>

<p>Number at time of creation: {{ numberCreated }}</p>
<div *ngFor="let message of men">
    {{message.contenido}}--{{message.fecha}}
</div>
<hr>

conversacion.component.ts

import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import {Mensaje} from "../../models/mensaje";

@Component({
    selector: 'app-conversacion',
    templateUrl: './conversacion.component.html',
    styleUrls: ['./conversacion.component.css']
})
export class ConversacionComponent implements OnInit {
    @Output() deleteSelf = new EventEmitter<void>();
    @Input() numberCreated: number;
    @Input() men:Mensaje[];
    @Input() destino:number;

    constructor() { }

    ngOnInit() {
    }


}

여기에 이미지 설명 입력

카일 앤더슨

ID에 대한 입력을 구성 요소에 추가하고 자체 이미 터 삭제를 변경하여 번호를 방출하고이를 사용하여 alreadyDone 배열을 업데이트하십시오.

dialog.component.html

import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import {Mensaje} from "../../models/mensaje";

@Component({
    selector: 'app-conversacion',
    templateUrl: './conversacion.component.html',
    styleUrls: ['./conversacion.component.css']
})
export class ConversacionComponent implements OnInit {
    @Output() deleteSelf = new EventEmitter<number>();
    @Input() numberCreated: number;
    @Input() men:Mensaje[];
    @Input() destino:number;
    @Input() id: number;

    constructor() { }

    ngOnInit() {
    }


}

그런 다음 app.component.ts에서 deleteSelf 이미 터를보고있는 위치를 변경하여 다음과 같이하십시오.

component.instance.id= elemento.id;
const selfDeleteSub = component.instance.deleteSelf
                            .pipe(tap(x => {
                                this.alreadyDone = this.alreadyDone.filter(done => done != x);
                                component.destroy();}))
                            .subscribe();

dialog.component.html :

<button (click)="deleteSelf.emit(id)" style="background-color: blue; color: white">close window</button>

<p>Number at time of creation: {{ numberCreated }}</p>
<div *ngFor="let message of men">
    {{message.contenido}}--{{message.fecha}}
</div>
<hr>

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Angular 8에서 다른 구성 요소로 이동 한 후 구성 요소의 상태를 어떻게 저장할 수 있습니까?

분류에서Dev

Angular 2에서 동일한 파일의 구성 요소를 어떻게 사용할 수 있습니까?

분류에서Dev

파이썬 Tkinter에서 크기가 조정 된 이미지를 어떻게 표시 할 수 있습니까?

분류에서Dev

Angular에서 동적으로로드 된 HTML 요소를 어떻게 선택할 수 있습니까?

분류에서Dev

파괴적인 바이러스를 어떻게 추적 할 수 있습니까?

분류에서Dev

실시간으로 생성 된 이미지를 어떻게 최적화 할 수 있습니까?

분류에서Dev

Angular / Typescript의 DOM에서 축소 된 동안 요소의 높이를 어떻게 얻을 수 있습니까?

분류에서Dev

React-다른 js 파일의 한 구성 요소에서 다른 구성 요소로 API 데이터를 어떻게 전달할 수 있습니까?

분류에서Dev

Python의 x_train에서 파생 된 이미지의 프로세스를 재구성하는 문제를 어떻게 해결할 수 있습니까?

분류에서Dev

파이썬에서 실시간 음성 활동 감지를 어떻게 할 수 있습니까?

분류에서Dev

파이썬에서 동일한 uuid 시퀀스를 어떻게 생성 할 수 있습니까?

분류에서Dev

Lua에서 쉼표로 구분 된 return 문이 어떻게 함수 호출로 작동 할 수 있습니까?

분류에서Dev

동적으로 생성 된 div 요소에서 슬라이드 또는 페이드 토글을 어떻게 사용할 수 있습니까?

분류에서Dev

어떻게이 구글 맵에 마커를 표시 할 수 있습니까?

분류에서Dev

React Router를 사용하는 동안 메서드와 상태를 중첩 된 구성 요소에 어떻게 전달할 수 있습니까?

분류에서Dev

for 루프를 사용하여 생성 된 버튼을 어떻게 파괴 할 수 있습니까 (클릭 후 ...)

분류에서Dev

구성 파일에서 Angular 값을 어떻게 설정할 수 있습니까?

분류에서Dev

Angular2에서 각 구성 요소에 다른 데이터 서비스를 어떻게 주입 할 수 있습니까?

분류에서Dev

CSS 그리드에서 요소를 어떻게 이동할 수 있습니까?

분류에서Dev

React에서 다른 구성 요소의 인증 상태를 어떻게 동기화 할 수 있습니까?

분류에서Dev

Codename One에서 양식 구성 요소를 어떻게 다시 빌드 할 수 있습니까?

분류에서Dev

SSH 동적 전달에 사용할 소스 IP를 어떻게 구성 할 수 있습니까?

분류에서Dev

Typescript / Angular2에서 동적으로 유형이 지정된 개체를 어떻게 반환 할 수 있습니까?

분류에서Dev

Angular에서 TypeScript로 json 객체를 어떻게 표시 할 수 있습니까?

분류에서Dev

Python을 사용하여 파이프로 구분 된 파일에서 값의 큰 따옴표를 어떻게 검증 할 수 있습니까?

분류에서Dev

파일에 구문 강조 표시를 어떻게 표시 할 수 있습니까?

분류에서Dev

Angular 2의 부모 구성 요소에서 자식 구성 요소로 객체를 어떻게 전달할 수 있습니까?

분류에서Dev

PHP 페이지에서 데이터베이스에 저장된 이미지를 어떻게 표시 할 수 있습니까?

분류에서Dev

규칙을 사용하지만 동적으로 명명 된 구성 요소를 어떻게 등록 할 수 있습니까?

Related 관련 기사

  1. 1

    Angular 8에서 다른 구성 요소로 이동 한 후 구성 요소의 상태를 어떻게 저장할 수 있습니까?

  2. 2

    Angular 2에서 동일한 파일의 구성 요소를 어떻게 사용할 수 있습니까?

  3. 3

    파이썬 Tkinter에서 크기가 조정 된 이미지를 어떻게 표시 할 수 있습니까?

  4. 4

    Angular에서 동적으로로드 된 HTML 요소를 어떻게 선택할 수 있습니까?

  5. 5

    파괴적인 바이러스를 어떻게 추적 할 수 있습니까?

  6. 6

    실시간으로 생성 된 이미지를 어떻게 최적화 할 수 있습니까?

  7. 7

    Angular / Typescript의 DOM에서 축소 된 동안 요소의 높이를 어떻게 얻을 수 있습니까?

  8. 8

    React-다른 js 파일의 한 구성 요소에서 다른 구성 요소로 API 데이터를 어떻게 전달할 수 있습니까?

  9. 9

    Python의 x_train에서 파생 된 이미지의 프로세스를 재구성하는 문제를 어떻게 해결할 수 있습니까?

  10. 10

    파이썬에서 실시간 음성 활동 감지를 어떻게 할 수 있습니까?

  11. 11

    파이썬에서 동일한 uuid 시퀀스를 어떻게 생성 할 수 있습니까?

  12. 12

    Lua에서 쉼표로 구분 된 return 문이 어떻게 함수 호출로 작동 할 수 있습니까?

  13. 13

    동적으로 생성 된 div 요소에서 슬라이드 또는 페이드 토글을 어떻게 사용할 수 있습니까?

  14. 14

    어떻게이 구글 맵에 마커를 표시 할 수 있습니까?

  15. 15

    React Router를 사용하는 동안 메서드와 상태를 중첩 된 구성 요소에 어떻게 전달할 수 있습니까?

  16. 16

    for 루프를 사용하여 생성 된 버튼을 어떻게 파괴 할 수 있습니까 (클릭 후 ...)

  17. 17

    구성 파일에서 Angular 값을 어떻게 설정할 수 있습니까?

  18. 18

    Angular2에서 각 구성 요소에 다른 데이터 서비스를 어떻게 주입 할 수 있습니까?

  19. 19

    CSS 그리드에서 요소를 어떻게 이동할 수 있습니까?

  20. 20

    React에서 다른 구성 요소의 인증 상태를 어떻게 동기화 할 수 있습니까?

  21. 21

    Codename One에서 양식 구성 요소를 어떻게 다시 빌드 할 수 있습니까?

  22. 22

    SSH 동적 전달에 사용할 소스 IP를 어떻게 구성 할 수 있습니까?

  23. 23

    Typescript / Angular2에서 동적으로 유형이 지정된 개체를 어떻게 반환 할 수 있습니까?

  24. 24

    Angular에서 TypeScript로 json 객체를 어떻게 표시 할 수 있습니까?

  25. 25

    Python을 사용하여 파이프로 구분 된 파일에서 값의 큰 따옴표를 어떻게 검증 할 수 있습니까?

  26. 26

    파일에 구문 강조 표시를 어떻게 표시 할 수 있습니까?

  27. 27

    Angular 2의 부모 구성 요소에서 자식 구성 요소로 객체를 어떻게 전달할 수 있습니까?

  28. 28

    PHP 페이지에서 데이터베이스에 저장된 이미지를 어떻게 표시 할 수 있습니까?

  29. 29

    규칙을 사용하지만 동적으로 명명 된 구성 요소를 어떻게 등록 할 수 있습니까?

뜨겁다태그

보관