首页 文章

如何在angular4中应用来自ts的反应形式的自定义指令?

提问于
浏览
0

我正在使用rective表单从组件构建自定义,遵循https://stackblitz.com/angular/ekboynmekgq?file=src%2Fapp%2Fdynamic-form-question.component.html给出的指导

对于验证消息我也在创建一个自定义组件,请参考https://plnkr.co/edit/km7nGR8DjyE4l6tH5JEC?p=preview

在上面的第二个plunker链接中给出了自定义指令方法,但问题是自定义指令直接应用于html表单元素而不是表单ts

没关系,我们可以像这样应用自定义属性指令

<form>
<input type="text" customDirective>
</from>

现在我想使用结构看起来像的custon输入组件来构建表单

<form>
<custom-input></cutom-input>
<custom-dropdown></custom-dropdown>
</form>

有一件事我没有说明,如何应用来自ts的属性指令与自定义错误componet(第二个链接)

请任何人有个主意请帮助我

1 回答

  • 0

    这个中间链接 - https://medium.com/@tarik.nzl/angular-2-custom-form-control-with-validation-json-input-2b4cf9bc2d73 by tarik 可能会让您更好地了解如何操作 .

    验证器组件

    import { Component, Input, forwardRef } from '@angular/core';
    import { ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl, Validator } from '@angular/forms';
    
    @Component({
        selector: 'json-input',
        template:
            `
            <textarea
              [value]="jsonString" 
              (change)="onChange($event)" 
              (keyup)="onChange($event)">
    
            </textarea>
            `,
        providers: [
        {
          provide: NG_VALUE_ACCESSOR,
          useExisting: forwardRef(() => JsonInputComponent),
          multi: true,
        },
        {
          provide: NG_VALIDATORS,
          useExisting: forwardRef(() => JsonInputComponent),
          multi: true,
        }]        
    })
    export class JsonInputComponent implements ControlValueAccessor, Validator {
        private jsonString: string;
        private parseError: boolean;
        private data: any;
    
        // this is the initial value set to the component
        public writeValue(obj: any) {
            if (obj) {
                this.data = obj;
                // this will format it with 4 character spacing
                this.jsonString = JSON.stringify(this.data, undefined, 4); 
            }
        }
    
        // registers 'fn' that will be fired wheb changes are made
        // this is how we emit the changes back to the form
        public registerOnChange(fn: any) {
            this.propagateChange = fn;
        }
    
        // validates the form, returns null when valid else the validation object
        // in this case we're checking if the json parsing has passed or failed from the onChange method
        public validate(c: FormControl) {
            return (!this.parseError) ? null : {
                jsonParseError: {
                    valid: false,
                },
            };
        }
    
        // not used, used for touch input
        public registerOnTouched() { }
    
        // change events from the textarea
        private onChange(event) {
    
            // get value from text area
            let newValue = event.target.value;
    
            try {
                // parse it to json
                this.data = JSON.parse(newValue);
                this.parseError = false;
            } catch (ex) {
                // set parse error if it fails
                this.parseError = true;
            }
    
            // update the form
            this.propagateChange(this.data);
        }
    
        // the method set in registerOnChange to emit changes back to the form
        private propagateChange = (_: any) => { };
    }
    

相关问题