programing

Angular 2 구성 요소 @입력이 작동하지 않음

mailnote 2023. 8. 9. 20:57
반응형

Angular 2 구성 요소 @입력이 작동하지 않음

구성 요소에 속성 값을 전달하려고 계속 시도하고 있습니다.제가 읽은 바로는 모든 것이 정확해 보입니다.하지만 그것은 여전히 작동하지 않습니다.내 테스트 값은 화면과 콘솔에 null로 출력됩니다. :(

테스트 구성 요소는 다음과 같습니다.

import {Component, Input} from 'angular2/angular2';

@Component({
    selector: 'TestCmp',
    template: `Test Value : {{test}}`
})

export class TestCmp {

    @Input() test: string;

    constructor()
    {
        console.log('This if the value for user-id: ' + this.test);
    }
}

이것이 상위 페이지에서 구성 요소를 호출하는 방법입니다.

<TestCmp [test]='Blue32'></TestCmp>

페이지 렌더링 시 테스트 값이 비어 있습니다.'테스트 값:'만 표시됩니다.

'테스트 값: Blue32' 대신 사용합니다.

제가 주목할 만한 네 가지 사항이 있습니다.

  • 루트 구성 요소에 입력을 전달하고 있습니다. 이 입력은 작동하지 않습니다.
  • @alexpods가 언급했듯이, 당신은 CamelCase를 사용하고 있습니다.그러면 안 됩니다.
  • 문자열 대신 식을 전달하고 있습니다.[test]즉, angular2는 다음과 같은 변수를 찾고 있습니다.Blue32생줄을 건네는 대신에.
  • 생성자를 사용하고 있습니다.이 방법은 사용할 수 없습니다. 보기가 초기화된 후에 데이터 바인딩 속성이 초기화되어야 합니다(OnInit에 대한 문서 참조).

그래서 몇 가지 수정 사항만 있으면 작동할 것입니다.

예제가 베타 1로 업데이트됨

import {Component, Input} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';

@Component({
  selector : 'childcmp',
  template: `Test Value : {{test}}`
})
class ChildCmp {
    @Input() test: string;
    ngOnInit() {
        console.log('This if the value for user-id: ' + this.test);
    }
}

@Component({
    selector: 'testcmp',
    template : `<childcmp [test]="'Blue32'"></childcmp>`
    directives : [ChildCmp]
})
export class TestCmp {}

bootstrap(TestCmp);

예제로 이 plnkr을 참조하십시오.

갱신하다

나는 사람들이 여전히 이 답에 도달한다는 것을 알고, 그래서 나는 plnkr을 베타 1로 업데이트했고, 나는 설명에서 한 점을 수정했습니다: 당신은 ningAfterView의 입력에 액세스할 수 있습니다.Init. 그러나 ngOnInit 내의 라이프사이클 초기에 액세스할 수 있습니다.

다음과 같이 큰따옴표로 문자열을 둘러싸는 것은 다음과 같습니다.

<TestCmp [test]="'Blue32'"></TestCmp>

대괄호 []를 사용하는 경우 Angular는 속성 바인딩을 사용하고 따옴표 안에 있는 식을 수신하기를 기대하며 구성 요소 클래스에서 'Blue32'라는 속성 또는 템플릿 내부의 변수를 찾습니다.

문자열을 자식 구성 요소에 값으로 전달하려면 다음과 같이 전달할 수 있습니다.

<child-component childProperty='passing string'></child-component>

또는 어떤 이유로 괄호를 사용하려는 경우:

<child-component [childProperty]="'note double quotes'"></child-component>

그런 다음 child.component.ts에 다음과 같이 입력합니다.

import { Component, Input } from "@angular/core";

@Component({})
export class ChildComponent {

    @Input()
    childProperty: string;

}

이 각도 클래스는 정적 속성에 대한 트릭을 만들 수 있습니다.요소 참조 https://angular.io/docs/ts/latest/api/core/index/ElementRef-class.html

import {ElementRef} from 'angular2/core'

constructor(elementRef: ElementRef) {
    elementRef.nativeElement.getAttribute('api')
}

내게 도움이 된 것을 공유하는 것:

Angular 4 앱에 입력 추가

두 가지 구성 요소가 있다고 가정합니다.

  • parent-component
  • child-component

우리는 약간의 가치를 전달하고 싶었습니다.parent-componentchild-component예를 들면@Inputparent-component.htmlchild-component.ts다음은 구현을 설명하는 예입니다.

parent-component.html다음과 같이 표시됩니다.

<child-component [someInputValue]="someInputValue"></child-component>

parent-component.ts다음과 같이 표시됩니다.

  
  class ParentComponent {

  someInputValue = 'Some Input Value';

}

child-component.html다음과 같이 표시됩니다.

<p>Some Input Value {{someInputValue}}</p>

child-component.ts다음과 같이 표시됩니다.


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

@Component({
  selector: 'child-component',
  templateUrl: './child-component.html'
})
export class ChildComponent implements OnInit {

  @Input() someInputValue: String = "Some default value";

  @Input()
  set setSomeInputValue(val) {
    this.someInputValue += " modified";
  }

  constructor() {
    console.log('someInputValue in constructor ************** ', this.someInputValue); //someInputValue in constructor ************** undefined
  }

  ngOnInit() {
    console.log('someInputValue  in ngOnInit ************** ', this.someInputValue); //someInputValue  in ngOnInit ************** Some Input Value
  }
}

다과같다니습음의 하십시오.@Input는 내에서 값있는 안에서 할 수 .ngOnInit() 내가아 안에 .constructor().

Angular 2/4의 객체 참조 동작

Javascript에서는 객체가 참조로 저장됩니다.

이 정확한 동작은 Angular 2/4의 도움을 받아 재현할 수 있습니다. 다음은 구현을 설명하는 예입니다.

parent-component.ts다음과 같이 표시됩니다.

  
  class ParentComponent {

  someInputValue = {input: 'Some Input Value'};

}

parent-component.html다음과 같이 표시됩니다.

  
{{someInputValue.input}}



child-component.html다음과 같이 표시됩니다.



Some Input Value {{someInputValue}}

change input

child-component.ts다음과 같이 표시됩니다.


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

@Component({
  selector: 'child-component',
  templateUrl: './child-component.html'
})
export class ChildComponent implements OnInit {

  @Input() someInputValue = {input:"Some default value"};

  @Input()
  set setSomeInputValue(val) {
    this.someInputValue.input += " set from setter";
  }

  constructor() {
    console.log('someInputValue in constructor ************** ', this.someInputValue); //someInputValue in constructor ************** undefined
  }

  ngOnInit() {
    console.log('someInputValue  in ngOnInit ************** ', this.someInputValue); //someInputValue  in ngOnInit ************** Some Input Value
  }

  changeInput(){
    this.someInputValue.input += " changed";
  }
}

changeInput() 의가를 변것니다입킬화의 됩니다.someInputValueChildComponent&ParentComponent그들의 언급 때문에. 이후로, 터부.someInputValue는 에서참됨ParentComponentsomeInputValue 목적어 - 변화ChildComponentsomeInputValue 개체가 값을 변경합니다.ParentComponentsomeInputValue 대상입니다. 이것은 정확하지 않습니다.참조는 절대 변경되지 않습니다.

여기서의 문제는 페이지의 라이프 사이클과 관련이 있을 수 있다고 생각합니다.생성자 내부에서 this.test의 값이 null이기 때문입니다.그러나 만약 내가 콘솔에 값을 푸시하는 함수에 연결된 템플릿에 버튼을 추가한다면(내가 생성자에서 하고 있는 것과 동일), 이 .test는 실제로 값을 가질 것입니다.

망치처럼 보이지만 입력을 다음과 같은 물체에 감을 수 있습니다.

<TestCmp [test]='{color: 'Blue32'}'></TestCmp>

그리고 수업을 바꾸세요.

class ChildCmp {
    @Input() test: any;
    ngOnInit() {
        console.log('This if the value for user-id: ' + this.test);
    }
}

하위 구성 요소의 맨 위에 이와 같은 입력을 가져와야 합니다.

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

각도 교호작용에 @Input을 사용하는 경우.@Angular Team이 로컬 변수 또는 정적 변수를 사용하도록 제한하지 않는 것처럼 JSON 개체에서 부모에서 자식으로 데이터를 전달하는 것이 항상 선호되는 접근 방식입니다.

컨텍스트에서 하위 구성 요소의 값에 액세스하려면 생성자에 관계없이 OnInit(){} 수명 후크 주기를 사용합니다.

그게 도움이 될 겁니다.건배.

이 문제가 발생했을 때 컴파일 오류가 발생하여 먼저 수정해야 했습니다(순환 종속성을 해결해야 함).

언급URL : https://stackoverflow.com/questions/33326376/angular-2-component-input-not-working

반응형