source

@Input() 값은 항상 정의되지 않습니다.

lovecheck 2023. 7. 26. 22:11
반응형

@Input() 값은 항상 정의되지 않습니다.

다음을 만들었습니다.user photo component그것은 필요합니다.@Input()value. 이 값은 userId입니다.값이 전달되면 다음에서 정보를 검색합니다.Firebase이 userId에 연결합니다. 연결되지 않으면 다른 작업을 수행합니다.

내 사용자 사진 구성 요소

import { Component, OnInit, OnDestroy, Input } from '@angular/core';

@Component({
    selector: 'user-photos',
    templateUrl: './user-photos.component.html',
    styleUrls: ['./user-photos.component.css']
})

export class UserPhotoComponent implements OnInit {

    @Input() userId: string;

    constructor() { 

        console.log('userId is:',this.userId);

    }


    ngOnInit() {


    }

    ngOnDestroy() {

    }
}

보시다시피 userId를 다음과 같이 선언했습니다.@Input()지금 나의edit-profile component다음 항목이 있습니다.

<user-photos [userId]="TestingInput"></user-photos>

이제 User Photo 구성 요소가 렌더링됩니다.h1태그가 나타나지만 userId는 항상 정의되지 않습니까?

개발자 콘솔에 오류가 나타나지 않아 제가 뭘 잘못했는지 잘 모르겠습니다.

다음 시간에 초기화됩니다.ngOnInit생성자가 아닙니다. (Angular Life Cycle Hooks 설명서참조하십시오.)

ngOnInit() {
  console.log('userId is:',this.userId);
}

또한 문자열과 같은 리터럴을 전달하고 대괄호를 사용하려는 경우[]값을 단일 눈금으로 묶어서 문자열로 전달해야 합니다.

<user-photos [userId]="'TestingInput'"></user-photos>

포함하는 식을 포함하는 구성 요소의 컨텍스트에서 평가하므로 포함하지 않으면 이름이 지정된 속성/필드를 검색하고 전달하려고 시도합니다.TestingInput정의되지 않습니다(해당 이름의 필드가 있는 경우 제외)

저의 경우 부모 템플릿에서 *ngIf = "isLoaded"를 먼저 사용해야 했습니다.

상위 구성 요소

    <div *ngIf = "isLoaded">
       <app-child-component [dataToChild]="dataFromParent"> </app-child-component>
    </div>

하위 구성 요소

      @Input() dataToChild: any;
        constructor() { }
        ngOnInit(): void {
             console.log(this.dataToChild);
         }

입력이 지연되면(예: 느린 웹 서비스) 웹 서비스에서 응답이 도착할 때까지 처음에는 값이 정의되지 않습니다.

이를 디버그하려면 ngOnChanges() 후크를 사용할 수 있습니다. ngOnChanges() 후크는 입력 값이 변경될 때마다 실행됩니다.

ngOnChanges() {
  console.log('data', this.data);
}

다음과 같은 것을 출력합니다.

data undefined<- Init에서 값이 아직 도착하지 않았습니다.

data here it is!<- 값 도착 지연

저 같은 경우에는, 제가 그냥 지나쳤어요.undefinedAngular가 정의되지 않은 경우를 기본 시나리오와 동일하게 처리할 것이라고 가정했습니다.이 가정은 Angular의 성분 상호 작용 문서에 명확하게 설명되어 있지 않더라도 잘못된 것이었습니다.다음은 사용 사례 시나리오입니다.

parent.component.vmdk:

...
[mVal]="undefined"
...

child.component.ts:

...
@input('mVal')
mVal: boolean = true
...

의 가치mVal될 것이다undefined그리고 아닌true예상하신 대로

Angular는 상위 구성 요소에 정의되지 않은 경우에만 값을 true(기본 대소문자)로 만듭니다. 그렇지 않으면 값을 그대로 전달합니다.undefined).

값이 구성 요소의 생성자에 정의되어 있지 않은지 또는 구성 요소의 생성자에 정의되어 있지 않은지 확인하여 이 문제를 해결할 수 있습니다.

TestingInput이 변수이고 값이 아닌 경우 추가하는 것이 좋습니다.*ngIf="TestingInput"

<user-photos [userId]="TestingInput" *ngIf="TestingInput "></user-photos>

api를 호출하는 경우 응답 지연으로 인해 빈 값이 전달될 수 있습니다.

저는 이 멍청한 @입력 실수에 많은 시간을 보냈습니다.다음과 같아야 합니다.

<user-photos
  [userId]="TestingInput">
</user-photos>

그리고 아닌

<user-photos>
  [userId]="TestingInput"
</user-photos>

아마도 누군가가 나처럼 구문을 실수했다면 도움이 될 것입니다.

하드 코딩된 문자열을 매개 변수로 사용하려면 단일 눈금 사용

<app-mycomponent [inputProperty]="'test'"></app-mycomponent>

질문에 대한 답변

@Input() 값은 항상 정의되지 않습니다.

ngOnInit에서 정의되지 않은 이유는 구성 요소가 초기화된 시점에서 userId를 실제로 전달하지 않았기 때문입니다.

<user-photos [userId]="TestingInput"></user-photos>

OnInit() 함수에서 @Input 값을 얻으려면 다음과 같은 작업을 수행합니다.

내 사용자 사진 구성 요소

import { Component, OnInit, OnDestroy, Input } from '@angular/core';

@Component({
    selector: 'user-photos',
    templateUrl: './user-photos.component.html',
    styleUrls: ['./user-photos.component.css']
})

export class UserPhotoComponent implements OnInit {

    @Input() userId: string;

    constructor() {  }

    ngOnInit() {
     setTimeout(() => {
         console.log('userId is:',this.userId);  // You will get the @Input value
     });
    }

    ngOnDestroy() {

    }
}

이 대답들 중 어떤 것도 나에게 효과가 없다, 내가 사랑 해결책을 찾은 후에,

HTML로

<app-opportunityTable [tableNAme]="'OPPORTUNITY'"></app-opportunityTable>

하위 구성 요소

@Component( {
    selector: 'app-opportunityTable',
    templateUrl: './opportunityTable.component.html',
    styleUrls: ['./opportunityTable.component.css'],
    inputs: ['tableNAme']
} )

export class opportunityTable implements OnInit {
         ngOnInit() {
        console.log( "this is it" + this.tableNAme )
         }
}

입력이 여러 개인 경우에도 정의할 수 있으며, 내 Angular 버전에서는 다음과 같습니다.

export class Foo {
    @Input() bar: string; // fine
    @Input() baz: string; // does not exist (console.log(this) does not show it)
}

당신이 그것을 건네주든 또한 중요하지 않습니다.Angular의 이전 버전에서는 이를 허용하지 않는 것 같습니다.입력이 여러 개 필요한 경우 필드가 여러 개인 한 개체를 전달합니다.

언급URL : https://stackoverflow.com/questions/42123170/input-value-is-always-undefined

반응형