简体   繁体   English

Angular 2 form.value属性未定义

[英]Angular 2 form.value property is undefined

I'm trying to use the name and [(ngModel)] template driven forms syntax for the first time, on a custom control which uses a controlValueAccessor which I am also using for the first time. 我想使用name[(ngModel)]模板驱动的形式首次语法,其上使用了一个自定义的控制controlValueAccessor这我也是用的第一次。

When I enter some words into my <input> then log my form.value to the console, I see the name of the form field that I added but it is still undefined: 当我在<input>输入一些单词,然后将form.value记录到控制台时,我看到添加的form字段的名称,但它仍未定义:

Object {keywords: undefined}

If I programmatically set a value for result.keywords, then when I log the form.value to the console, the keywords property is populated. 如果我以编程方式为result.keywords设置一个值,那么当我将form.value记录到控制台时,将填充keyword属性。 The binding from the model to the form.value is working. 从模型到form.value的绑定正在工作。 The binding from the view (html input control) to the model is not working. 从视图(html输入控件)到模型的绑定无效。

ngOnInit() {
    this.result = new Result();
    this.result.keywords = ["aaa"]; <----works
}

The above will show ["aaa"] in the console but it will not show anything in the view. 以上内容将在控制台中显示[“ aaa”],但在视图中将不显示任何内容。 How can I correctly get the keywords property of the form to populate? 如何正确获取要填充的表单的keywords属性?

My code: 我的代码:

My form: 我的表格:

 <form class="text-uppercase" (ngSubmit)="onSubmit(findForm.value, findForm.valid)" #findForm="ngForm">
        <vepo-input 
           [placeholder]='"keywords (optional)"' 
           [id]='"keywordsInput"'
           name="keywords"
           [(ngModel)]="result.keywords">
        </vepo-input>
    </form>

input-component.ts: input-component.ts:

import { Component, ViewChild, ElementRef, Input, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

const noop = () => {
};

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => InputComponent),
    multi: true
};


@Component({
    selector: 'vepo-input',
    templateUrl: 'app/shared/subcomponents/input.component.html',
    styleUrls: ['app/shared/subcomponents/input.component.css'],
    providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})

export class InputComponent implements ControlValueAccessor {
    @Input() private placeholder: string;
    @Input() private id: string;

    //The internal data model
    private innerValue: any = '';

    //Placeholders for the callbacks which are later providesd
    //by the Control Value Accessor
    private onTouchedCallback: () => void = noop;
    private onChangeCallback: (_: any) => void = noop;

    //get accessor
    get value(): any {
        return this.innerValue;
    };

    //set accessor including call the onchange callback
    set value(v: any) {
        if (v !== this.innerValue) {
            this.innerValue = v;
            this.onChangeCallback(v);
        }
    }

    //Set touched on blur
    onBlur() {
        this.onTouchedCallback();
    }

    //From ControlValueAccessor interface
    writeValue(value: any) {
        if (value !== this.innerValue) {
            this.innerValue = value;
        }
    }

    //From ControlValueAccessor interface
    registerOnChange(fn: any) {
        this.onChangeCallback = fn;
    }

    //From ControlValueAccessor interface
    registerOnTouched(fn: any) {
        this.onTouchedCallback = fn;
    }

}

input.component.html: input.component.html:

<input  class="form-item-input"
            placeholder={{placeholder}} 
            id={{id}} />
<label   attr.for="{{id}}"
         class="form-item-right-icon input-icon">
</label>

My form is actually a lot bigger than what I posted but I don't wanna overload everyone with irrelevant code. 我的表单实际上比我发布的表单大很多,但我不想用不相关的代码重载所有人。 For the sake of completeness here is the full form.ts file: 为了完整起见,这里是完整的form.ts文件:

import {
    Component,
    ViewChild,
    ElementRef,
    EventEmitter,
    Output,
    OnInit
} from '@angular/core';
import {
    FormGroup,
    FormBuilder,
    Validators,
    ControlValueAccessor
} from '@angular/forms';
import { ResultService } from '../../../services/result.service';
import { Result } from '../../../models/all-models';
import { HighlightDirective } from '../../../directives/highlight.directive';
import { DistanceUnitsComponent } from './distance-units.component';
import { MultiselectComponent } from './multiselect-find-category.component';
import { MultiselectFindMealTypeComponent } from
    './multiselect-find-meal-type.component';
import { AreaComponent } from './area-picker.component';
import { NumberPickerComponent } from './number-picker.component';
import { InputComponent } from '../../../shared/subcomponents/input.component';

@Component({
    selector: 'find-form',
    templateUrl: 'app/find-page/subcomponents/find-page/find-form.component.html',
    styleUrls: ['app/find-page/subcomponents/find-page/find-form.component.css'],
    providers: [ResultService]
})
export class FindFormComponent implements OnInit {

    @ViewChild('multiselectFindCategory')
    private multiselectFindCategory: MultiselectComponent;
    @ViewChild('multiselectFindMealType')
    private multiselectFindMealType: MultiselectFindMealTypeComponent;
    @ViewChild('distanceUnits') private distanceUnits: DistanceUnitsComponent;
    @ViewChild('numberPicker') private numberPicker: NumberPickerComponent;
    @ViewChild('areaInput') private areaInput: AreaComponent;
    @ViewChild('keywordsInput') private keywordsInput: InputComponent;

    @Output() private onResultsRecieved:
    EventEmitter<Object> = new EventEmitter<Object>();
    @Output() private onSubmitted: EventEmitter<boolean> =
    new EventEmitter<boolean>();

    private categoryError: string = 'hidden';
    private mealTypeError: string = 'hidden';
    private areaError: string = 'hidden';

    private findForm: FormGroup;
    private submitted: boolean = false;
    private result: Result;

    private displayMealCategories: boolean = false;
    private mealSelected: boolean = false;
    private place: google.maps.Place;

    constructor(private resultService: ResultService,
        private formBuilder: FormBuilder,
        el: ElementRef) { }

    ngOnInit() {
        this.result = new Result();
    }

    private setCategoryErrorVisibility(
        multiselectFindCategory: MultiselectComponent
    ): void {
        if (multiselectFindCategory.selectedCategories.length < 1 &&
            !multiselectFindCategory.allSelected &&
            this.submitted) {
            this.categoryError = 'visible';
        } else {
            this.categoryError = 'hidden';
        }
    }

    private setMealTypeErrorVisibility(
        multiselectFindMealType: MultiselectFindMealTypeComponent
    ): void {
        if (multiselectFindMealType) {
            if (multiselectFindMealType.selectedCategories.length < 1 &&
                !multiselectFindMealType.allSelected &&
                this.submitted) {
                this.mealTypeError = 'visible';
            } else {
                this.mealTypeError = 'hidden';
            }
        }
    }

    private setAreaErrorVisibility(): void {
        if (this.areaInput.areaInput.nativeElement.value) {
            if (!this.areaInput.address) {
                this.areaError = 'visible';
                this.areaInput.areaInput.nativeElement.setCustomValidity("Please select from dropdown or leave blank.");
            } else {
                this.areaError = 'hidden';
                this.areaInput.areaInput.nativeElement.setCustomValidity("");
            }
        } else {
            this.areaError = 'hidden';
            this.areaInput.areaInput.nativeElement.setCustomValidity("");
        }
    }

    private onCategoriesChanged(): void {
        this.setCategoryErrorVisibility(this.multiselectFindCategory);
        this.mealSelected = this.multiselectFindCategory.mealSelected;
        if (!this.mealSelected) {
            this.mealTypeError = 'hidden';
        }
    }

    private onMealTypesChanged(): void {
        this.setMealTypeErrorVisibility(this.multiselectFindMealType);
    }

    private onAreaChanged(areaEntered: any): void {
        this.setStateOfDistanceControls(areaEntered.areaEntered);
        this.areaError = "hidden";
        this.areaInput.areaInput.nativeElement.setCustomValidity("");
        if (areaEntered.place) {
            this.place = areaEntered.place;
        }
    }

    private setStateOfDistanceControls(areaEntered: any): void {
        if (areaEntered.areaEntered) {
            this.distanceUnits.isEnabled = true;
            this.numberPicker.isEnabled = true;
        } else {
            this.distanceUnits.isEnabled = false;
            this.numberPicker.isEnabled = false;
        }
        this.distanceUnits.setImage();
    }

    private getResults(): void {
        var results: Result[] = [];
        results = this.resultService.getResults();
        if (results) {
            this.onResultsRecieved.emit({
                recieved: true,
                results: results,
                place: this.place
            });
        }
    }

    private onSubmit(model: any, isValid: boolean): void {

        console.log(model, isValid);


        // this.submitted = true;
        // this.setCategoryErrorVisibility(this.multiselectFindCategory);
        // this.setMealTypeErrorVisibility(this.multiselectFindMealType);
        // this.setAreaErrorVisibility();
        // if (this.areaError === "hidden" &&
        //  this.categoryError === "hidden" &&
        //  this.mealTypeError === "hidden") {
        //  this.onSubmitted.emit(true);
        //  this.getResults();
        // }
    }
}

Alright, here's my stab at your intent with a working plunker to back up the work: 好吧,这是我刺耳的意图,与一个正在工作的矮人一起备份工作:

In your input.component.html you need to make sure you have the bindings set up into ngModel 在您的input.component.html中,您需要确保已将绑定设置为ngModel

<input class="form-item-input" [(ngModel)]="value" [placeholder]="placeholder" id="{{id}}" />

Aside from that, there's really nothing else to do. 除此之外,实际上没有其他事情可做。

Here's the plunker: http://plnkr.co/edit/HleTVBnvd8ePgMClAZS2?p=preview 这是the客: http ://plnkr.co/edit/HleTVBnvd8ePgMClAZS2?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM