Angular 2-在父级初始化后将数据传递给子级组件 [英] Angular 2 - Passing data to Child component after Parent initialisation

查看:57
本文介绍了Angular 2-在父级初始化后将数据传递给子级组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父组件,该组件通过服务从服务器获取数据.我需要将其中一些数据传递给Child组件.

I have a parent component which is getting data from a server through a service. I need some of this data to be passed to the Child component.

我一直在尝试使用通常的@Input()传递此数据,但是正如我期望的那样,我在Child组件中获取的数据是undefined.

I've been trying to pass this data with the usual @Input() however as I expected the data I'm getting in the Child component is undefined.

示例

父项

@Component({
    selector: 'test-parent',
    template: `
        <test-child [childData]="data"></test-child>
    `
})

export class ParentComponent implements OnInit {
    data: any;

    ngOnInit() {
        this.getData();
    }

    getData() {
        // calling service and getting data
        this.testService.getData()
            .subscribe(res => {
                this.data = res;
            });
    }
}

子组件

@Component({
    selector: 'test-child',
    template: `
        <!-- Content for child.... -->
    `
})

export class ChildComponent implements OnInit {
    @Input() childData: any;

    ngOnInit() {
        console.log(childData); // logs undefined
    }
}

我将示例保持简单,以显示我要执行的操作.我的问题是初始化后是否有可能将数据传递给孩子.我不确定,但是在这种情况下双向数据绑定会有所帮助吗?

I've kept the example simple so as to show what I'm trying to do. My question is whether it's possible to pass data to the child after the initialisation. I'm not sure but would two-way data binding help in this case?

更多调查

按照发布的答案进行操作,我尝试使用ngOnChanges生命周期挂钩.我遇到的问题是更新数据时未触发ngOnChanges函数.数据是一个对象,这就是为什么我认为未检测到更改的原因.

Following the posted answers I've tried using the ngOnChanges lifecycle hook. The issue I'm having is that the ngOnChanges function is not being fired when the data is updated. The data is an object which is why I think the changes are not being detected.

子组件中的更新代码

@Component({
    selector: 'test-child',
    template: `
        <!-- Content for child.... -->
    `
})

export class ChildComponent implements OnChanges {
    @Input() childData: any;

    ngOnChanges() {
        console.log(childData); // logs undefined
    }
}

我已经尝试使用Angular团队的"Plunker上的实时示例"进行了测试,该示例展示了生命周期挂钩.在测试中,我更新了OnChangesComponent以传递一个对象,如在示例中看到的那样,在更新对象时ngOnChanges并未检测到更改. (这也显示在此问题中)

I've tried a test with the Live Examples on Plunker from the Angular team showcasing the Lifecycle Hooks. In the test I've updated the OnChangesComponent to pass an object which as can be seen in the example when updating an object the ngOnChanges is not detecting the change. (This is also shown in this question)

https://plnkr.co/edit/KkqwpsYKXmRAx5DK4cnV

似乎ngDoCheck可以帮助解决此问题,但在我看来,从长远来看,这不会帮助性能,因为此生命周期挂钩可以检测到所有更改.

Seems that the ngDoCheck could help solve this issue, but it seems to me that it would not help performance in the long run as every change is detected by this Lifecycle Hook.

我也知道我可以使用@ViewChild()来访问子组件并设置所需的变量,但是我认为对于这种用例来说,这没有多大意义.

Also I know that I could probably use the @ViewChild() to access the Child Component and set the variables that I need, but I don't think that for this use-case it makes much sense.

发布更多代码以帮助更好地解释

父项

@Component({
    selector: 'test-parent',
    template: `
        <test-child [childType]="numbers" [childData]="data" (pickItem)="pickNumber($event)">
            <template let-number>
                <span class="number" [class.is-picked]="number.isPicked">
                    {{ number.number }}
                </span>
            </template>
        </test-child>
        <test-child [childType]="letters" [childData]="data" (pickItem)="pickLetter($event)">
            <template let-letter>
                <span class="letter" [class.is-picked]="letter.isPicked">
                    {{ letter.displayName }}
                </span>
            </template>
        </test-child>
        <button (click)="submitSelections()">Submit Selection</button>
    `
})

export class ParentComponent implements OnInit {
    data: any;
    numbersData: any;
    lettersData: any;

    ngOnInit() {
        this.getData();
    }

    getData() {
        // calling service and getting data for the game selections
        this.testService.getData()
            .subscribe(res => {
                this.data = res;
                setChildData(this.data);
            });
    }

    setChildData(data: any) {
        for(let i = 0; i < data.sections.length; i++) {
            if(data.sections[i].type === 'numbers') {
                this.numbersData = data.sections[i];
            }

            if(data.sections[i].type === 'letters') {
                this.lettersData = data.sections[i];
            }
        }
    }

    pickNumber(pickedNumbers: any[]) {
        this.pickedNumbers = pickedNumbers;
    }

    pickLetter(pickedLetters: any[]) {
        this.pickedLetters = pickedLetters;
    }

    submitSelections() {
        // call service to submit selections
    }
}

子组件

@Component({
    selector: 'test-child',
    template: `
        <!--
            Content for child...
            Showing list of items for selection, on click item is selected
        -->
    `
})

export class ChildComponent implements OnInit {
    @Input() childData: any;
    @Output() onSelection = new EventEmitter<Selection>;

    pickedItems: any[];

    // used for click event
    pickItem(item: any) {
        this.pickedItems.push(item.number);

        this.onSelection.emit(this.pickedItems);
    }
}

这或多或少是我拥有的代码.基本上,我有一个父级来处理子级组件中的选择,然后将这些选择提交给服务.我需要将某些数据传递给孩子,因为我试图让孩子以服务期望的格式返回对象.这将帮助我不要在父组件中创建服务期望的整个对象.同样,从子级发回服务期望的意义上来说,它将使子级可重用.

That's more or less the code that I have. Basically I have a parent that handles selections from child components and then I submit these selections to the service. I need to pass certain data to the child because I'm trying to have the object that the child returns in the format that the service is expecting. This would help me not to create the whole object expected by the service in the parent component. Also it would make the child reuseable in the sense that it sends back what the service expects.

更新

我很感谢用户仍在发布有关此问题的答案.请注意,上面发布的代码对我有用.我遇到的问题是,在特定模板中,我有一个错字,导致数据为undefined.

I appreciate that users are still posting answers on this question. Note that the code that has been posted above worked for me. The issue I had was that in a particular template I had a typo which caused for the data to be undefined.

希望这对您有所帮助:)

Hope that it's proving to be helpful :)

推荐答案

由于开始时未定义数据,因此可以使用* ngIf ='data'

Since data is undefined at start, you can postpone it with *ngIf='data'

<div *ngIf='data'>
   <test-child [childData]="data"></test-child>
</div>

或者您可以在组件上实现ControlValueAccessor并通过ngModel和ngModelChange传递它

Or you can implement ControlValueAccessor on your component and pass it by ngModel with ngModelChange

<test-child [ngModel]="data?" (ngModelChange)="data? ? data= $event : null"></test-child>

这篇关于Angular 2-在父级初始化后将数据传递给子级组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆