首页 文章

输出子组件后将元素传递给父组件

提问于
浏览
0

我只是从子组件输出一些内容,我想知道如何在此之后将父模板中的元素传递给父组件 .

通常我会创建一个元素的变量(在这种情况下是#textArea),但不知怎的,我无法传递它 . 有人知道这是怎么做的吗?

Parent template: editReview($event, textArea) is the function that gets sent from the child component. I receive the $event part in my editReview fucntion, but not the element reference.

<app-review-list [movie]="movie" (editReview)="editReview($event, textArea)"></app-review-list>

    <hr>

    <form ngNativeValidate (ngSubmit)="onSubmit(f)" #f="ngForm">
        <div class="form-group">
            <label for="review">Write A Review:</label>
            <textarea
                    #textArea
                    (keyup.enter)="onSubmit(f)"
                    rows="4"
                    cols="50"
                    type="text"
                    id="review"
                    ngModel
                    class="form-control"
                    name="review"
                    required
            ></textarea>
        </div>
        <button type="button" class="btn btn-danger" (click)="onClear(f)">Clear</button>
        <button class="btn btn-primary" type="submit">Save</button>
    </form>

This is the parent component. In the editReview method, console.log(content) gives me the result I desired, but the other console.log gives me nothing

import {Component, ElementRef, Input, OnInit} from "@angular/core";
import {NgForm} from "@angular/forms";
import {ReviewService} from "./review.service";
import {ActivatedRoute} from "@angular/router";


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

export class ReviewComponent implements OnInit{

    movieId;
    @Input('movie') movie;


    constructor(private reviewService: ReviewService, private route: ActivatedRoute){}


    editReview(content, elem){
        console.log(content);
        console.log(elem)
    }


}

1 回答

  • 0

    如果在结构指令中的任何位置(例如 *ngIf )上的元素上设置了该模板引用变量,则将 temple reference variable 传递给方法会出现问题 .

    如果您的实际代码(不是已发布的代码段)中有结构指令,则说明了该问题 . 如果不这样做,则不清楚为什么它不起作用 .

    在任何一种情况下,另一种方法是使用ViewChild装饰器 .

    Parent component

    在父组件中,添加以下声明:

    @ViewChild('textArea') myElementRef: ElementRef;
    

    并修改 editReview 方法如下:

    editReview(content){
        console.log(content);
        console.log(this.myElementRef);
    }
    

相关问题