账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    angular中父子组件怎么相互控制
    54
    0

    父组件的点击事件可以显示子组件并隐藏自身部分内容
    子组件的点击事件可以显示父组件隐藏的内容,并隐藏自身
    父组件app
    <div class="container">
    <div class="row">

    <div class="col-md-7">
      <p>app中的内容,打开home时隐藏,从home返回时显示</p>
      <button class="btn btn-primary">打开home</button>
    </div>
    <div class="col-md-4">
      <app-home></app-home>
    </div>

    </div>
    </div>

    子组件home
    <p>我是 home</p>
    <button class="btn btn-primary">返回app</button>

    1
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 10 元积分
        全部回答
    • 0
    • 慾朢變得荒傏 普通会员 1楼

      在Angular中,父子组件可以通过事件(如click,change等)和通信协议(如XMLHttpRequest)来相互控制。以下是一个简单的例子:

      假设我们有两个子组件,子组件A和子组件B,它们有一个共同的父组件C。父组件C有一个按钮,点击这个按钮会发送一个GET请求到子组件A。

      首先,我们需要在父组件C中创建一个按钮,然后在父组件C中定义一个函数来处理按钮的点击事件。

      ```typescript import { Component, OnInit } from '@angular/core';

      @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { ngOnInit() { this.sendRequest(); }

      sendRequest() { // 发送GET请求到子组件A const xhr = new XMLHttpRequest(); xhr.open('GET', 'http://localhost:8080/appA'); xhr.onload = function () { if (xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send(); } } ```

      在子组件A中,我们需要监听父组件C的发送请求事件,并处理这个事件。

      ```typescript import { Component, OnInit } from '@angular/core';

      @Component({ selector: 'app-appA', templateUrl: './app-appA.component.html', styleUrls: ['./app-appA.component.css'] }) export class AppAComponent implements OnInit { ngOnInit() { this.sendRequest(); }

      sendRequest() { // 发送GET请求到父组件C const xhr = new XMLHttpRequest(); xhr.open('GET', 'http://localhost:8080/appC'); xhr.onload = function () { if (xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send(); } } ```

      在父组件C中,我们需要在按钮的点击事件处理函数中调用子组件A的sendRequest函数。

      ```typescript import { Component, OnInit } from '@angular/core';

      @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { ngOnInit() { this.sendRequest(); }

      sendRequest() { // 发送GET请求到子组件A const xhr = new XMLHttpRequest(); xhr.open('GET', 'http://localhost:8080/appA'); xhr.onload = function () { if (xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send(); } } ```

      这就是在Angular中,父子组件通过事件和通信协议相互控制的基本方式。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部