0
I’ve been trying to fire a function of a parent component into a child component and I can’t, someone’s done something like?
0
I’ve been trying to fire a function of a parent component into a child component and I can’t, someone’s done something like?
1
You need to create a service. Use the ng g s command /.
Once done, in your service you will put the logic of your function and import it into the parent and child component as follows:
Service:
@Injectable({
providedIn: 'root'
})
export class EspecialidadeService {
especialidadeVO: EspecialidadeVO;
private url = `${environment.apiUrl}especialidade`;
constructor(private auth: AuthService,
private http: HttpClient,
private router: Router
) { }
getEspecialidade() {
const body = {};
return this.http.post<EspecialidadeVO>(this.url + 'pesquisa/pesquisar', body).pipe(take(1));
}
Parent and child components:
@Component({
selector: 'app-especialidade-cadastro',
templateUrl: './especialidade-cadastro.component.html',
styleUrls: ['./especialidade-cadastro.component.css'],
preserveWhitespaces: true
})
export class EspecialidadeCadastroComponent implements OnInit {
form: FormGroup;
name = new FormControl('', [Validators.required, Validators.minLength(3)]);
private id: number;
constructor(
private especialidade: EspecialidadeService,
private route: ActivatedRoute,
private router: Router,
) { }
ngOnInit(): void {
this.route.params.subscribe(
(params: any) => {
this.id = params.id;
if (this.id !== undefined) {
const result = this.especialidade.especialidadeById(this.id);
result.subscribe( res => {
this.name.setValue(res.nomeEspecialidade.trim());
});
}
}
);
}
Note that in the component I create in the constructor an instance of Specialties with specialty name, then in onInit I use the command this.especialidade.especialidadeById, which is the function created in the service. So this function is visible to anyone who creates an instance of this service.
There are ways you can pass the parameters from one to the other, but you said you want to access functions and not values, the ideal form in angular is using services.
Browser other questions tagged angular angular-6 angular-8
You are not signed in. Login or sign up in order to post.
Probably what you want is simple, but you’re doing it wrong!
– LeAndrade