I think this may be a duplicate question.
I have a component B in which there is a function saveContact()
. I want to call this function from another function of component A .
So I
Imported component B in component A. Then created a viewChild
@ViewChild(ContactformComponent) contactForm: ContactformComponent;
Called the function
saveContactForm() { this.contactForm.saveContact(); }
When I run the application I get error TypeError: Cannot read property 'saveContact' of undefined
.
Can someone tell me what I am doing wrong.
Parent Component
import { ContactformComponent } from './forms/contactform/contactform.component';
@Component({
selector: 'app-insert',
templateUrl: './insert.component.html',
styleUrls: ['./insert.component.scss'],
animations: [routerTransition()]
})
export class InsertComponent implements OnInit {
@ViewChild(ContactformComponent) contactForm;
saveContactForm() {
this.contactForm.saveContact();
}
}
Child Component
@Component({
selector: 'app-contactform',
templateUrl: './contactform.component.html',
styleUrls: ['./contactform.component.scss']
})
export class ContactformComponent implements OnInit {
contactForm: FormGroup;
... // Form Code
public saveContact() {
const savedContact = {
contactType: this.contactType,
contactDescription: this.contactTypeDescription,
contactSubType: this.contactSubType,
contactSubTypeDescription: this.contactSubTypeDescription,
referenceNumber: this.referenceNumber,
lastVerifiedDate: this.parseDate(this.contactlastVerifiedDate.toString()),
startDate: this.parseDate(this.contactStartDate.toString()),
endDate: this.parseDate(this.contactEndDate.toString())
};
this.savedContact.emit(savedContact);
this.snackbar.open('Contact Saved,Click on Create Customer or Fill more
Details', 'Close', {
duration: 5000
});
}