简体   繁体   中英

Angular 8 component not getting rendered

Current scenario

  • An angular component (angular 8) with a text box and text area.
  • The component built using the command ""build": "ng build --prod --output-hashing=none"" (in the package.json)
  • Then the output min file is copied to another external folder containing an HTML file.
  • The component is displayed using the generated component tag.

Issue

  • Angular component not getting rendered in a HTML page when 'formControlName' is used for binding the value of a text box (In angular project).

  • How to implement the form using "formGroup" and 'formControlName' then sould be able to use the component in an external HTML file.

Any help would be highly appreciated. Thanks in advance.

<--------html code-->

        <div>
        <form [formGroup]="generalRequestForm" (ngSubmit)="onSubmit()">
            <div class="mb-15 form-group">
                <select class="custom-select" formControlName="requests" id="requests" ngDefaultControl>
                    <option value="">Select Request Type</option>
                    <option *ngFor="let request of requests; let i = index" [value]="requests[i].id">
                        {{requests[i].name}}
                    </option>
                </select>
            </div>
            <div class="mb-15 form-group">
                <input type="text" class="form-control" placeholder="Item" formControlName="item" ngDefaultControl
                    autocomplete="off" />
                <div *ngIf="invalidItem" class="error">This field cannot be empty.</div>

            </div>
            <div class="mb-15 form-group">
                <textarea class="form-control comments" placeholder="Comments" formControlName="comments"
                    ngDefaultControl autocomplete="off"></textarea>
                <div *ngIf="invalidComments" class="error">This field cannot be empty.</div>

            </div>
            <div class="row align-items-center remember"></div>
            <div class="form-group">
                <button class="btn float-right submit_btn">Submit</button>
                <div *ngIf="invalidLogin" class="error">Invalid credentials.</div>
            </div>
        </form>
    </div>


**<-------ts code------->**

export class GeneralRequestComponent implements OnInit {
    generalRequestForm: FormGroup;
    invalidLogin: boolean = false;
    invalidItem: boolean = false;
    submitSuccess: boolean = false;
    invalidComments: boolean = false;
    requests;
    constructor(
        private formBuilder: FormBuilder,
        private router: Router,
        private apiService: ApiService
    ) {

        this.generalRequestForm = new FormGroup({
            item: new FormControl('', Validators.required),
            comments: new FormControl('', Validators.required),
            requests: new FormControl('', Validators.required),
        })

        of(this.getRequestType()).subscribe(requests => {
            this.requests = requests;
            this.generalRequestForm.controls.requests.patchValue(this.requests[0].id);
        });
    }

    onSubmit() {

        console.log("item...", this.generalRequestForm)
        if (!this.generalRequestForm.controls.item.value) {
            this.invalidItem = true;
            return;
        }
        else if (!this.generalRequestForm.controls.comments.value) {
            this.invalidComments = true;
            return;
        }
        else {
            alert("Your response has been recorded. Administrator would reach you before the time.")
            return;
        }
        if (this.generalRequestForm.invalid) {
            return;
        }
        const loginPayload = {
            item: this.generalRequestForm.controls.item.value,
            comments: this.generalRequestForm.controls.comments.value

        };
        this.apiService.login(loginPayload).subscribe(data => {
            if (data.status === 200) {
                window.localStorage.setItem('token', data.token);
                this.router.navigate(['home']);
            } else {
                this.invalidLogin = true;
                alert(data.message);
            }
        });
    }

    ngOnInit() {
        // window.localStorage.removeItem('token');
        // this.generalRequestForm = this.formBuilder.group({
        //     item: ['', Validators.compose([Validators.required])],
        //     comments: ['', Validators.required],
        //     requests: ['', Validators.required]
        // });

    }

    getRequestType() {
        return [
            { id: '1', name: 'Parking Slot' },
            { id: '2', name: 'Meal Card' },
            { id: '3', name: 'Infopark Sticker' },
            { id: '4', name: 'Address Proof' },
            { id: '5', name: 'Form 16' },
            { id: '6', name: 'Time Entry' },
            { id: '7', name: 'Other Request' }
        ];
    }
}

You may want to define a Form object in the typescript file (.ts), then bind it to the html form. This is called "reactive form", you can check out the documentation from angular on this subject:

https://angular.io/guide/reactive-forms

(it also contains an example to followup and gain more knowledge)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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